raj*_*123 0 python list python-itertools
我有一个包含元素的列表B。我想使用这些元素创建所有可能的对,如预期输出中所示。但我收到错误。我如何解决它?
import numpy as np
import itertools
B=[ 1, 2, 5, 7, 10, 11]
combination=[]
for L in range(len(B) + 1):
for subset in itertools.combinations(B, L):
combination.append([list(sub) for sub in subset])
combination
Run Code Online (Sandbox Code Playgroud)
错误是
in <listcomp>
combination.append([list(sub) for sub in subset])
TypeError: 'int' object is not iterable
Run Code Online (Sandbox Code Playgroud)
预期输出是
[1,2],[1,5],[1,7],[1,10],[1,11],
[2,1],[2,5],[2,7],[2,10],[2,11],
[5,1],[5,2],[5,7],[5,10],[5,11],
[7,1],[7,2],[7,5],[7,10],[7,11],
[10,1],[10,2],[10,5],[10,7],[10,11],
[11,1],[11,2],[11,5],[11,7],[11,10]
Run Code Online (Sandbox Code Playgroud)
您正在寻找的combinations不是permutations:
>>> list(itertools.permutations(B, 2))
[(1, 2),
(1, 5),
(1, 7),
(1, 10),
(1, 11),
(2, 1),
(2, 5),
(2, 7),
(2, 10),
(2, 11),
(5, 1),
(5, 2),
(5, 7),
(5, 10),
(5, 11),
(7, 1),
(7, 2),
(7, 5),
(7, 10),
(7, 11),
(10, 1),
(10, 2),
(10, 5),
(10, 7),
(10, 11),
(11, 1),
(11, 2),
(11, 5),
(11, 7),
(11, 10)]
Run Code Online (Sandbox Code Playgroud)
要转换为列表:
# List comprehension
perm = [list(p) for p in itertools.permutations(B, 2)
# Functional programming
perm = list(map(list, itertools.permutations(B, 2)))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
177 次 |
| 最近记录: |