如何从Python列表中选取“x”个唯一数字?
我需要从一个列表中随机挑选出“x”个不重复的数字。比如说:
all_data = [1, 2, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 11, 12, 13, 14, 15, 15]
我该怎么挑选出像 [2, 11, 15]
这样的列表,而不是 [3, 8, 8]
呢?
7 个回答
9
其他人建议你使用 random.sample
。虽然这个建议是对的,但有一个细节大家都忽略了:
如果你的数据里有重复的项,那么每一个重复的项都有可能被选到。
所以,你需要把你的列表转换成一个集合,这样就可以避免重复的值:
import random
L = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
random.sample(set(L), x) # where x is the number of samples that you want
14
像这样:
all_data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
from random import shuffle
shuffle(all_data)
res = all_data[:3]# or any other number of items
或者:
from random import sample
number_of_items = 4
sample(all_data, number_of_items)
如果你的所有数据可能包含重复的条目,那么你需要先修改你的代码,去掉重复的部分,然后再使用洗牌或者抽样的方法:
all_data = list(set(all_data))
shuffle(all_data)
res = all_data[:3]# or any other number of items
150
这正是 random.sample()
这个函数的作用。
>>> random.sample(range(1, 16), 3)
[11, 10, 2]
补充说明: 我几乎可以肯定这不是你问的问题,但我还是想加一句:如果你想从一个包含重复项的集合中抽样,首先得把重复的部分去掉。
population = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]
population = list(set(population))
samples = random.sample(population, 3)