I am working on a program which I need to repeatedly make a subset list with 2 items out of a list with n items.
for example let's assume this is the list (The actual list has more items):
list = [50, 100, 250, 500, 750, 1000, 2000]
I need a function which takes list and a number like 2 and then give back a list like this:
[[50,100], [50,250], [50, 500], [50, 750], [50, 1000], [50, 2000], [100, 250],...]
As you can see I don't want items with the same numbers in the answer like [50,100], [100, 50].
I figure this out as the algorithm for finding All the subsets of list :
from itertools import chain, combinations
def powerset(iterable):
xs = list(iterable)
return list(chain.from_iterable(combinations(xs,n) for n in range(len(xs)+1)))
Thanks for the helps.
This will do the job:
l = [50, 100, 250, 500, 750, 1000, 2000]
from itertools import combinations
res=list(combinations(l,2))
print(res)
This prints
[(50, 100),
(50, 250),
(50, 500),
(50, 750),
(50, 1000),
(50, 2000),
(100, 250),
(100, 500),
(100, 750),
(100, 1000),
(100, 2000),
(250, 500),
(250, 750),
(250, 1000),
(250, 2000),
(500, 750),
(500, 1000),
(500, 2000),
(750, 1000),
(750, 2000),
(1000, 2000)]
What's wrong with combinations(l,2)
?
print list(combinations(l,2))
# [(50, 100), (50, 250), (50, 500), (50, 750), (50, 1000), (50, 2000), (100, 250), (100, 500), (100, 750), (100, 1000), (100, 2000), (250, 500), (250, 750), (250, 1000), (250, 2000), (500, 750), (500, 1000), (500, 2000), (750, 1000), (750, 2000), (1000, 2000)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.