简体   繁体   English

随机选择列表中的两个元素

[英]Randomly choosing two elements in a list

Is there a better way to select two distinct elements from a list? 有没有更好的方法从列表中选择两个不同的元素?

foo = ['1','a','3','f','ed']

elt1 = random.choice(foo)
elt2 = random.choice(foo)

while elt2 == elt1:
    elt2 = random.choice(foo)

Yes, use random.sample() : 是的,请使用random.sample()

elt1, elt2 = random.sample(foo, 2)

random.sample() will pick k unique elements from the given population, at random: random.sample()将从给定总体中随机选择k唯一元素:

Return a k length list of unique elements chosen from the population sequence. 返回从填充序列中选择的唯一元素的k个长度的列表。 Used for random sampling without replacement. 用于随机抽样而无需更换。

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

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

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