我需要从列表中挑出“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]
的列表?
这正是random.sample()
所做的。
>>> random.sample(range(1, 16), 3)
[11, 10, 2]
编辑:我几乎可以肯定这不是你提出的问题,但是我被推荐包括这个评论:如果你想从中获取样本的人口包含重复项,你必须先删除它们:
population = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]
population = set(population)
samples = random.sample(population, 3)
像这样的东西:
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可能包含重复的条目而不是修改代码以首先删除重复项,然后使用shuffle或sample:
all_data = list(set(all_data))
shuffle(all_data)
res = all_data[:3]# or any other number of items
其他人建议你使用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
另一种方式,当然使用所有解决方案,您必须确保原始列表中至少有3个唯一值。
all_data = [1,2,2,3,4,5,6,7,8,8,9,10,11,11,12,13,14,15,15]
choices = []
while len(choices) < 3:
selection = random.choice(all_data)
if selection not in choices:
choices.append(selection)
print choices
您还可以使用itertools.combinations
和random.shuffle
生成随机选择列表。
all_data = [1,2,2,3,4,5,6,7,8,8,9,10,11,11,12,13,14,15,15]
# Remove duplicates
unique_data = set(all_data)
# Generate a list of combinations of three elements
list_of_three = list(itertools.combinations(unique_data, 3))
# Shuffle the list of combinations of three elements
random.shuffle(list_of_three)
输出:
[(2, 5, 15), (11, 13, 15), (3, 10, 15), (1, 6, 9), (1, 7, 8), ...]
import random
fruits_in_store = ['apple','mango','orange','pineapple','fig','grapes','guava','litchi','almond']
print('items available in store :')
print(fruits_in_store)
my_cart = []
for i in range(4):
#selecting a random index
temp = int(random.random()*len(fruits_in_store))
# adding element at random index to new list
my_cart.append(fruits_in_store[temp])
# removing the add element from original list
fruits_in_store.pop(temp)
print('items successfully added to cart:')
print(my_cart)
输出:
items available in store :
['apple', 'mango', 'orange', 'pineapple', 'fig', 'grapes', 'guava', 'litchi', 'almond']
items successfully added to cart:
['orange', 'pineapple', 'mango', 'almond']