在Python中获取列表的所有组合,而不在一行中重复两次相同的字符
以前有人问过许多类似的问题,但我没有找到一个与我相同的用例 假设我有以下列表: 列表=[1,2,3] 如果同一个数字不重复两次,如何打印此列表的所有组合。我想要的输出是:在Python中获取列表的所有组合,而不在一行中重复两次相同的字符,python,python-3.x,python-2.7,recursion,combinations,Python,Python 3.x,Python 2.7,Recursion,Combinations,以前有人问过许多类似的问题,但我没有找到一个与我相同的用例 假设我有以下列表: 列表=[1,2,3] 如果同一个数字不重复两次,如何打印此列表的所有组合。我想要的输出是: 1 2 3 12 13 21 23 31 32 123 132 213 232 312 321 我将如何实现这一点 大多数解决方案的输出如下: 1 2 3 12 13 32 123 132 213 232 312 321 这里缺少21、23和31,因为我认为12、32和13是相同的组合,我不希望代码这样做 提前谢谢我很确定
1
2
3
12
13
21
23
31
32
123
132
213
232
312
321
我将如何实现这一点
大多数解决方案的输出如下:
1
2
3
12
13
32
123
132
213
232
312
321
这里缺少21、23和31,因为我认为12、32和13是相同的组合,我不希望代码这样做
提前谢谢我很确定这是一个复制品,但我找不到好的。迭代所有所需长度时,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)]
或:
可怕的恶心的一个班轮似乎做到了这一点:
[
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]这更优雅您的问题的标题具有误导性:它说的是“一行中没有字符重复两次,而您的意思似乎是“没有任何字符重复”
[
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:])])
]