如何在python中迭代地从列表中获取一定数量的元素

时间:2018-02-02 18:22:46

标签: python python-3.x

假设我有一个列表

l= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

我想要一个排列,每次运行后给我一个新列表,它只包含主列表中的三个元素,这些列表只出现一次。 E.g。

l1= [1,2,3]
l2= [1,2,4]
l3= [1,2,5]
...
l8= [1,2,10]
l9= [1,3,4]
l10= [1,3,5]
l11= [1,3,6]
...
ln= [8,9,10]

我怎么能在python中做这样的事情? 谢谢你!

1 个答案:

答案 0 :(得分:0)

您可以使用itertools.combinations

l= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
s = [('l'+str(b), list(i)) for b, i in enumerate(itertools.combinations(l, 3), start=1)]

输出:

[('l1', [1, 2, 3]), ('l2', [1, 2, 4]), ('l3', [1, 2, 5]), ('l4', [1, 2, 6]), ('l5', [1, 2, 7]), ('l6', [1, 2, 8]), ('l7', [1, 2, 9]), ('l8', [1, 2, 10]), ('l9', [1, 3, 4]), ('l10', [1, 3, 5]), ('l11', [1, 3, 6]), ('l12', [1, 3, 7]), ('l13', [1, 3, 8]), ('l14', [1, 3, 9]), ('l15', [1, 3, 10]), ('l16', [1, 4, 5]), ('l17', [1, 4, 6]), ('l18', [1, 4, 7]), ('l19', [1, 4, 8]), ('l20', [1, 4, 9]), ('l21', [1, 4, 10]), ('l22', [1, 5, 6]), ('l23', [1, 5, 7]), ('l24', [1, 5, 8]), ('l25', [1, 5, 9]), ('l26', [1, 5, 10]), ('l27', [1, 6, 7]), ('l28', [1, 6, 8]), ('l29', [1, 6, 9]), ('l30', [1, 6, 10]), ('l31', [1, 7, 8]), ('l32', [1, 7, 9]), ('l33', [1, 7, 10]), ('l34', [1, 8, 9]), ('l35', [1, 8, 10]), ('l36', [1, 9, 10]), ('l37', [2, 3, 4]), ('l38', [2, 3, 5]), ('l39', [2, 3, 6]), ('l40', [2, 3, 7]), ('l41', [2, 3, 8]), ('l42', [2, 3, 9]), ('l43', [2, 3, 10]), ('l44', [2, 4, 5]), ('l45', [2, 4, 6]), ('l46', [2, 4, 7]), ('l47', [2, 4, 8]), ('l48', [2, 4, 9]), ('l49', [2, 4, 10]), ('l50', [2, 5, 6]), ('l51', [2, 5, 7]), ('l52', [2, 5, 8]), ('l53', [2, 5, 9]), ('l54', [2, 5, 10]), ('l55', [2, 6, 7]), ('l56', [2, 6, 8]), ('l57', [2, 6, 9]), ('l58', [2, 6, 10]), ('l59', [2, 7, 8]), ('l60', [2, 7, 9]), ('l61', [2, 7, 10]), ('l62', [2, 8, 9]), ('l63', [2, 8, 10]), ('l64', [2, 9, 10]), ('l65', [3, 4, 5]), ('l66', [3, 4, 6]), ('l67', [3, 4, 7]), ('l68', [3, 4, 8]), ('l69', [3, 4, 9]), ('l70', [3, 4, 10]), ('l71', [3, 5, 6]), ('l72', [3, 5, 7]), ('l73', [3, 5, 8]), ('l74', [3, 5, 9]), ('l75', [3, 5, 10]), ('l76', [3, 6, 7]), ('l77', [3, 6, 8]), ('l78', [3, 6, 9]), ('l79', [3, 6, 10]), ('l80', [3, 7, 8]), ('l81', [3, 7, 9]), ('l82', [3, 7, 10]), ('l83', [3, 8, 9]), ('l84', [3, 8, 10]), ('l85', [3, 9, 10]), ('l86', [4, 5, 6]), ('l87', [4, 5, 7]), ('l88', [4, 5, 8]), ('l89', [4, 5, 9]), ('l90', [4, 5, 10]), ('l91', [4, 6, 7]), ('l92', [4, 6, 8]), ('l93', [4, 6, 9]), ('l94', [4, 6, 10]), ('l95', [4, 7, 8]), ('l96', [4, 7, 9]), ('l97', [4, 7, 10]), ('l98', [4, 8, 9]), ('l99', [4, 8, 10]), ('l100', [4, 9, 10]), ('l101', [5, 6, 7]), ('l102', [5, 6, 8]), ('l103', [5, 6, 9]), ('l104', [5, 6, 10]), ('l105', [5, 7, 8]), ('l106', [5, 7, 9]), ('l107', [5, 7, 10]), ('l108', [5, 8, 9]), ('l109', [5, 8, 10]), ('l110', [5, 9, 10]), ('l111', [6, 7, 8]), ('l112', [6, 7, 9]), ('l113', [6, 7, 10]), ('l114', [6, 8, 9]), ('l115', [6, 8, 10]), ('l116', [6, 9, 10]), ('l117', [7, 8, 9]), ('l118', [7, 8, 10]), ('l119', [7, 9, 10]), ('l120', [8, 9, 10])]