A random word from one of two lists

Cameron Simpson cs at cskk.id.au
Fri Jan 1 18:18:20 EST 2021


On 01Jan2021 22:58, Bischoop <Bischoop at vimart.net> wrote:
>I have two lists *animal* and *fruit* and I try to get a random variable
>animal or fruit and then random word from that list.
>I thought that dictionary(*words*) could help me but no succes, the only way I've
>done partially what was with list *kinds* and by using two times
>random.choice. However print(kind) return me a list not a variable:
>animal or fruit so now I'm kinda confuse if I can achieve that.
>
>import random
>animal = ['koala', 'kangaroo']
>fruit = ['banana', 'apple']

This is fine.

>kinds = [animal,fruit]

This probably isn't what you intend. Print out kinds:

    print(repr(kinds))

>words = {'animals': animal, 'fruits': fruit}

I suspect you want, after this line:

    kinds = list(words.keys())

which gets you a list of the dictionary keys. Print that, too, to see 
the difference.

>kind = random.choice(kinds)
>print(kind)

When the earlier stuff works, this should be a string.

>word = random.choice(kind)

This picks a random character from the string. Probably not what you 
want. You want to pick from the list of animals or fruits. Since you 
(will) have the word "animals" or "fruits" in "kind", how do you 
reference the appropriate list?

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list