How do you pick “x” number of unique numbers from a list in Python?
我需要从列表中选择"x"个非重复随机数字。例如:
1 | all_data = [1, 2, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 11, 12, 13, 14, 15, 15] |
我如何挑选一个像
这正是
1 2 | >>> random.sample(range(1, 16), 3) [11, 10, 2] |
编辑:我几乎可以肯定这不是您所要求的,但我被要求将此评论包括在内:如果要从包含重复项的样本中提取样本的总体,则必须首先删除它们:
1 2 3 | population = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1] population = set(population) samples = random.sample(population, 3) |
号
其他人建议您使用
If the population contains repeats,
then each occurrence is a possible
selection in the sample.
号
因此,需要将列表转换为一个集合,以避免重复的值:
1 2 3 | 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 |
。
像这样:
1 2 3 4 | 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 |
或:
1 2 3 | from random import sample number_of_items = 4 sample(all_data, number_of_items) |
。
如果所有_数据都可能包含重复项,则修改代码以先删除重复项,然后使用shuffle或sample:
1 2 3 | all_data = list(set(all_data)) shuffle(all_data) res = all_data[:3]# or any other number of items |
您还可以使用
1 2 3 4 5 6 7 8 9 10 | 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) |
输出:
1 | [(2, 5, 15), (11, 13, 15), (3, 10, 15), (1, 6, 9), (1, 7, 8), ...] |
。
另一种方法,当然,对于所有的解决方案,您必须确保原始列表中至少有3个唯一的值。
1 2 3 4 5 6 7 | 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 |
。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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) |
输出:
1 2 3 4 | items available in store : ['apple', 'mango', 'orange', 'pineapple', 'fig', 'grapes', 'guava', 'litchi', 'almond'] items successfully added to cart: ['orange', 'pineapple', 'mango', 'almond'] |
。