从 python 列表中获取元素的唯一组合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18201690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get unique combinations of elements from a python list
提问by Allen
Edit: This is not a exact duplicate of How to get all possible combinations of a list's elements?
编辑:这不是如何获得列表元素的所有可能组合的完全重复?
This topic is about finding unique combinations while the other topic is about finding ALL combinations.
本主题是关于查找唯一组合,而另一个主题是关于查找所有组合。
If I have a python list:
如果我有一个 python 列表:
L = [1,2,3,4]
what's the best way to get all the possible unique combinationsof 3 elements from the list like below:
从列表中获取3 个元素的所有可能的唯一组合的最佳方法是什么:
["1,2,3", "1,2,4", "2,3,4", "3,4,1"]
The order of the elements in the combinations doesn't matter. For example, "1,2,3"
and "3,2,1"
will be considered the same combination.
组合中元素的顺序无关紧要。例如,"1,2,3"
和"3,2,1"
将被视为相同的组合。
I can probably write a few loops to do this but I think there might be a one-liner which can do the same.
我可能会写几个循环来做到这一点,但我认为可能有一个单线可以做到这一点。
采纳答案by Ashwini Chaudhary
You need itertools.combinations
:
>>> from itertools import combinations
>>> L = [1, 2, 3, 4]
>>> [",".join(map(str, comb)) for comb in combinations(L, 3)]
['1,2,3', '1,2,4', '1,3,4', '2,3,4']