Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Making Combinations (Python)

$
0
0

In Python, is there a better way to get the set of combinations of n elements from a k-element set than nested for loops or list comprehensions?

For example, say from the set [1,2,3,4,5,6] I want to get [(1,2),(1,3),(1,4),(1,5),(1,6),(2,3),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6),(4,5),(4,6),(5,6)]. Is there a better of of making it than

nums=[1,2,3,4,5,6]doubles=[]for a in nums:    for b in nums[a+1:]:        doubles.append((a,b))

? It's okay if the elements of the list we end up with are sets, tuples, or lists; I just feel there should be an easier way to do this.


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>