2 回答
TA贡献1777条经验 获得超10个赞
很确定这是重复的,但我找不到好的。itertools.permutations当您迭代所有所需的长度时,做您想要的:
from itertools import permutations, chain
lst = [1,2,3]
list(chain(*(permutations(lst, n) for n in range(1, len(lst)+1))))
# [(1,), (2,), (3,), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
或:
for p in chain(*(permutations(lst, n) for n in range(1, len(lst)+1))):
print(''.join(map(str, p)))
1
2
3
12
13
21
23
31
32
123
132
213
231
312
321
TA贡献1818条经验 获得超11个赞
令人作呕的单线似乎可以解决问题:
[
int(''.join(map(str, number)))
for n in range(1,4)
for number in itertools.product([1,2,3], repeat = n)
if not any([first == second for first, second in zip(number, number[1:])])
]
输出:
[1, 2, 3, 12, 13, 21, 23, 31, 32, 121, 123, 131, 132, 212, 213, 231, 232, 312, 313, 321, 323]
添加回答
举报