如何生成列表组合? [英] How to generate list combinations?

查看:52
本文介绍了如何生成列表组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个列表的列表,该列表表示数字0和1的所有可能组合。列表的长度为n。

I want to produce a list of lists that represents all possible combinations of the numbers 0 and 1. The lists have length n.

输出应如下所示。对于n = 1:

The output should look like this. For n=1:

[ [0], [1] ]

对于n = 2:

[ [0,0], [0, 1], [1,0], [1, 1] ]

对于n = 3:

[ [0,0,0], [0, 0, 1], [0, 1, 1]... [1, 1, 1] ]

我看着itertools.combinations,但是这会产生元组,而不是列表。 [0,1]和[1,0]是不同的组合,而只有一个元组(0,1)(顺序无关紧要)。

I looked at itertools.combinations but this produces tuples, not lists. [0,1] and [1,0] are distinct combinations, whereas there is only one tuple (0,1) (order doesn't matter).

任何提示或建议?我尝试了一些递归技术,但没有找到解决方案。

Any hints or suggestions? I have tried some recursive techniques, but I haven't found the solution.

推荐答案

您在寻找 itertools.product(...)

>>> from itertools import product
>>> list(product([1, 0], repeat=2))
[(1, 1), (1, 0), (0, 1), (0, 0)]

如果要将内部元素转换为 list 类型,请使用列表理解

If you want to convert the inner elements to list type, use a list comprehension

>>> [list(elem) for elem in product([1, 0], repeat =2)]
[[1, 1], [1, 0], [0, 1], [0, 0]]

或者通过使用 map()

>>> map(list, product([1, 0], repeat=2))
[[1, 1], [1, 0], [0, 1], [0, 0]]

这篇关于如何生成列表组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆