我有一个列表,我随机打印其中一个项目,但我想从列表中打印另一个随机项目,我想100%确定它不是前一个。
import random
i = 0
Names = ["Andrew", 'John', 'Jacob','Bob']
for l in Names:
i += 1
c = random.randrange(0,i)
print(Names[c])
答案 0 :(得分:5)
使用random.sample从给定序列中选择唯一元素,例如
import random
Names = ['Andrew', 'John', 'Jacob', 'Bob']
choice = random.sample(Names, 2) # choose 2 unique names from Names
print(choice[0])
print(choice[1])
答案 1 :(得分:2)
random.shuffle(names)
names[0] # first pick
names[1] # second pick ... also guaranteed not to be first pick
另一种方法是在随机选择名称时从列表中删除名称
names =[...]
random1 = names.pop(random.randint(0,len(names)))
random2 = names.pop(random.randint(0,len(names)))