简体   繁体   中英

How do i use the random.choice of a list as a condition to what other lists to random.choice from?

Example:

element = ['Flaming', 'Cold']
fire_properties = ['of Fire', 'of Flame']
cold_properties = ['of Ice', 'of Frost']

Fairly simple. Wanted to make a text randomizer and end up with results such as "Flaming sword of Fire" according to this example. Unfortunately, i wasn't sure of how to make it so that the result from the first list would define from which list the second result would be.

how about such kind of solution: you construct a map of the possible combinations of adjective and noun and select one of them:

weapon_map = {"Flaming": ["Fire", "Inferno"], "Frozen": ["Cold", "Frost"]}
selection = random.choice(weapon_map.items())
print (selection[0] + " of " + random.choice(selection[1]))

This approach is easier to maintain and understand.

Well, I first wrote this one, but Boris's was more succinct, so I decided not to submit... might be a bit more readable for a beginner, though.

quality_list =  ['Flaming', 'Frozen', 'etc.']
quality = random.choice(quality_list)

item_list = ['Sword', 'Dagger', 'Mace', 'etc.']
item = random.choice(item_list)


hot_qualities = ['Flaming', ...]
cold_qualities = ['Frozen', ...]
hot_elements = ['Fire', 'Inferno']
cold_elements = ['Cold', 'Frost']

if quality in hot_qualities:
    element = random.choice(hot_elements)
elif quality in cold_qualities:
    element = random.choice(cold_elements)

# NB this is Python 2.X's print and string format, adjust accordingly for 3.X
print "%s %s of %s" % (quality, item, element)

Though in real project I'd generalize it further like Boris did.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM