Python:3个元素的排列

qq1*_*121 -2 python combinations list permutation

如何在Python中找到包含3个元素的列表的所有排列?

例如,输入

[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

会回来的

[1, 2, 3]
[1, 2, 4]
[1, 3, 4]
[2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

谢谢!

iCo*_*dez 6

你想使用itertools.combinations列表理解:

>>> from itertools import combinations
>>> lst = [1, 2, 3, 4]
>>> [list(x) for x in combinations(lst, 3)]
[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
>>>
Run Code Online (Sandbox Code Playgroud)

关于你的评论,你可以通过添加str.joinmap*来制作字符串列表:

>>> from itertools import combinations
>>> lst = [1, 2, 3, 4]
>>> [''.join(map(str, x)) for x in combinations(lst, 3)]
['123', '124', '134', '234']
>>>
Run Code Online (Sandbox Code Playgroud)

*注意: 您需要这样做,map(str, x)因为str.join需要一个可迭代的字符串.