![](/img/trans.png)
[英]How can I get all the combinations of a list given that two items can not be in the same list?
[英]How can I get all combinations of a list?
我正在尝试获取列表的所有组合。 这是一个例子:
>>> l = [1, 2, 3]
>>> combo = something
>>> print(combo)
[1, 2, 3, 12, 13, 21, 23, 31, 32, 123, 132, 213, 231, 312, 321]
这是我到目前为止所尝试的:
>>> import itertools
>>> numbers = [1, 2, 3]
>>> l = list(itertools.permutations(numbers))
>>> print(l)
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
如何获得 output [1, 2, 3, 12, 13, 21, 23, 31, 32, 123, 132, 213, 231, 312, 321]
?
工作代码:
import itertools
numbers = [1, 2, 3]
result = []
for n in range(1, len(numbers) + 1):
for x in itertools.permutations(numbers, n): # n - length of each permutation
result.append(int(''.join(map(str, x))))
print(result)
Output:
[1, 2, 3, 12, 13, 21, 23, 31, 32, 123, 132, 213, 231, 312, 321]
我相信您正在查看的 function 是:
itertools.combinations(iterable, r)
它在r元素中组合了可迭代的数组。
所以:
>>> import itertools
>>> numbers = [1,2,3]
>>> l = list(itertools.combinations(numbers,2)) # combinations of two
>>> print(l)
[(1, 2), (1, 3), (2, 3)]
您可以在文档中获得更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.