如何从python中的n个大小的列表中随机选择k个项目

时间:2017-12-31 20:52:34

标签: python algorithm

我想知道如何从n个大小的列表中随机选择所有可能组合的k项。

  

例如,设A = [1,2,3,4]和K = 3.然后它应该返回[1,2,3],[1,2,4],[1,3,4] ,[2,3,4]。

2 个答案:

答案 0 :(得分:4)

您正在寻找itertools.combinations。例如:

>>> my_list = A = [1, 2, 3, 4]
>>> k = 3

>>> from itertools import combinations
>>> list(combinations(my_list, k))
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

答案 1 :(得分:0)

如果结果中的排序很重要,您可以使用itertools.permutations来获取所有排列 - 将它们放入一个集合中可以删除源自列表中重复数字的重复项

import itertools

n = 3
my_list =  [1, 2, 3, 2 ,1]

print( set(itertools.permutations(my_list, n))) # or list, see below

输出:

{(1, 2, 1), (3, 1, 2), (2, 3, 2), (1, 3, 2), (3, 1, 1), (3, 2, 1), (1, 2, 2), 
 (1, 1, 3), (2, 2, 1), (2, 1, 1), (1, 3, 1), (2, 3, 1), (1, 2, 3), (1, 1, 2), ...} 
 # with set: 17 items

[(1, 2, 3), (1, 2, 2), (1, 2, 1), (1, 3, 2), (1, 3, 2), (1, 3, 1), (1, 2, 2), 
 (1, 2, 3), (1, 2, 1), (1, 1, 2), (1, 1, 3), (1, 1, 2), (2, 1, 3), (2, 1, 2), ...] 
 # with list: 60 items

排列和组合之间的差异:

# permutations - based on all values on any position in the resulttuple
[(1, 2, 3), (1, 2, 2), (1, 2, 1), (1, 3, 2), (1, 3, 2), (1, 3, 1), (1, 2, 2), (1
, 2, 3), (1, 2, 1), (1, 1, 2), (1, 1, 3), (1, 1, 2), (2, 1, 3), (2, 1, 2), (2, 1
, 1), (2, 3, 1), (2, 3, 2), (2, 3, 1), (2, 2, 1), (2, 2, 3), (2, 2, 1), (2, 1, 1
), (2, 1, 3), (2, 1, 2), (3, 1, 2), (3, 1, 2), (3, 1, 1), (3, 2, 1), (3, 2, 2),
(3, 2, 1), (3, 2, 1), (3, 2, 2), (3, 2, 1), (3, 1, 1), (3, 1, 2), (3, 1, 2), (2,
 1, 2), (2, 1, 3), (2, 1, 1), (2, 2, 1), (2, 2, 3), (2, 2, 1), (2, 3, 1), (2, 3,
 2), (2, 3, 1), (2, 1, 1), (2, 1, 2), (2, 1, 3), (1, 1, 2), (1, 1, 3), (1, 1, 2)
, (1, 2, 1), (1, 2, 3), (1, 2, 2), (1, 3, 1), (1, 3, 2), (1, 3, 2), (1, 2, 1), (
1, 2, 2), (1, 2, 3)]

# combinations - based on position in source list not on value order in tuple preserved
[(1, 2, 3), (1, 2, 2), (1, 2, 1), (1, 3, 2), (1, 3, 1), (1, 2, 1), (2, 3, 2), (2
, 3, 1), (2, 2, 1), (3, 2, 1)]

按任意键继续。 。