简体   繁体   English

列表重复N次的组合python

[英]combinations of list repeated N times python

I have a list l = [1, 2, 3, 4, 5] and would like to generate all possible combinations assuming the elements of l are repeated N times.我有一个列表l = [1, 2, 3, 4, 5]并希望生成所有可能的组合,假设l的元素重复N次。

Example: [1, 2, 3, 4, 5] with N = 2 would yield示例: [1, 2, 3, 4, 5] 与 N = 2 将产生

[1, 1], [1, 2], [1, 3], [1, 4], [1, 5]

[2, 1], [2, 2], [2, 3], [2, 4], [2, 5]

[3, 1], [3, 2], [3, 3], [3, 4], [3, 5]

[4, 1], [4, 2], [4, 3], [4, 4], [4, 5]

[5, 1], [5, 2], [5, 3], [5, 4], [5, 5]

Thanks!谢谢!

You want itertools.product :你想要itertools.product

>>> from itertools import product
>>> list(map(list, product([1, 2, 3, 4, 5], repeat=2)))
[[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [5, 1], [5, 2], [5, 3], [5, 4], [5, 5]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM