For example
['Apple','Orange','Grape']
From the list of
[['Apple'], ['Orange'], ['Grape'], ['Apple', 'Orange'], ['Apple', 'Grape'], ['Orange', 'Grape'], ['Apple', 'Orange', 'Grape']]
I want to get the output. Some combinations have only one element, and some have multiple elements. I know it's a list of 2 ^ n-1 answers, but when I actually tried to write it, I stumbled. Isn't it going to be a complicated nest?
I found a standard library that can be used in such cases. itertools --- Iterator generation function for efficient loop execution
Iterator | argument | result |
---|---|---|
combinations() | p,r | Tuple column of length r, no duplication in sorted order |
For example
test.py
import itertools
lis = [1,2,3,4]
for pair in itertools.combinations(lis, 2):
print(pair)
If you do the above, you will get the following results:
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
For the time being, change the argument and try again.
test2.py
import itertools
lis = [1,2,3,4]
for team in itertools.combinations(lis, 3):
print(team)
(1, 2, 3)
(1, 2, 4)
(1, 3, 4)
(2, 3, 4)
With itertools.combinations (), you can get all combination patterns (in tuples) with any number of elements in the ** list like this. ** ** Here, if you start with the number of elements from 1 and turn it to the list length with a for statement, it seems that you can get the answer you wanted first.
all_combinations.py
import itertools
lis=['Apple','Orange','Grape']
result = []
for n in range(1,len(lis)+1):
for conb in itertools.combinations(lis, n):
result.append(list(conb)) #Convert tuples to list type
print(result)
Execution result
[['Apple'], ['Orange'], ['Grape'], ['Apple', 'Orange'], ['Apple', 'Grape'], ['Orange', 'Grape'], ['Apple', 'Orange', 'Grape']]
If you use itertools, it seems that there will be more situations where you do not have to write nests, and it may be an essential item for paiza and competition pros. As mentioned in "Readable Code", I thought that if you make a habit of reading the standard library on a regular basis, you will be able to write good code.
It was an introduction to the standard library that I found useful!
Recommended Posts