繁体   English   中英

有没有一种简单的方法可以从列表中随机选择一个元素除外?

[英]Is there a simple way to randomly pick from a list with the exception of one element?

如果我想从这样的列表中随机选择,我得到了...

list=[a,b,c,d]

有没有一种简单的方法可以从列表中选择另一个元素,而无需再次选择 b ,而无需更改列表?

也许你可以使用random. sample random. sample

返回从种群序列或集合中选择的唯一元素的 ak 长度列表。 用于放回的随机抽样。

>>> import random
>>> l = ['a', 'b', 'c', 'd']
>>> random.sample(l, 3) # Pick 3 random elements without replacement from l
['c', 'd', 'a']

虽然 Shash Sinha 的答案肯定是您正在寻找的,但您也可以稍微玩一下递归(这确实改变了原始列表,所以它并不理想):

import random

choices = ['a', 'b', 'c', 'd']

def chooseRandom():
    
    if len(choices) > 0:

        choice = choices.pop(random.randint(0, len(choices)-1))

        print (f'Chosen Character: {choice}')
        print (f'Remaining Choices: {choices}')

        chooseRandom()
        
chooseRandom()

这将 output 类似于以下内容(取决于随机选择的内容):

Chosen Character: c
Remaining Choices: ['a', 'b', 'd']
Chosen Character: a
Remaining Choices: ['b', 'd']
Chosen Character: b
Remaining Choices: ['d']
Chosen Character: d
Remaining Choices: []
import copy
import random

list = ['a', 'b' , 'c', 'd']
list2 = copy.deepcopy(list)
random.shuffle(list2)
for i in list2:
   # i is now a random item from original list
   do_something(i)

当你需要一个随机项目时,你也可以从 list2 中弹出()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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