Python List random choice

半城伤御伤魂 提交于 2021-02-08 11:15:43

问题


Looking for a help / solution here.

a = [1,2,3]
b = [1,2,3]
c = [1,2,3]
d = [a,b,c]

random.choice(random.choice(d))

this gives me 1,2 or 3. But how to find which list variable this random function used out of a, b, c ? how can I use or what is the syntax of the index function for this ? for my program I have to pop the element the random choice returns.


回答1:


If you want to remove something from the randomly chosen list, you don't need to have the variable name. The list object itself will do.

In other words, just remove the selected number from the result that random.choice() gives you:

picked_list = random.choice(d)
picked = random.choice(picked_list)
picked_list.remove(picked)

If you must have some kind of name, don't use separate variables for the input lists. Use a dictionary:

lists = {
    'a': [1, 2, 3],
    'b': [1, 2, 3],
    'c': [1, 2, 3],
}
list_picked = random.choice(lists)  # returns 'a', 'b', or 'c'
picked = random.choice(lists[list_picked])
lists[list_picked].remove(picked)

Note that it'll be more efficient to just shuffle your lists up-front (putting them in random order), then pop elements as you need them:

d = [a, b, c]
for sublist in d:
    random.shuffle(sublist)

# later on
picked = random.choice(d).pop()  # remove the last element

You'll have to figure out what it means to have an empty list there though.



来源:https://stackoverflow.com/questions/44355406/python-list-random-choice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!