I am trying to get all combinations of a list. Here is an example:
>>> l = [1, 2, 3]
>>> combo = something
>>> print(combo)
[1, 2, 3, 12, 13, 21, 23, 31, 32, 123, 132, 213, 231, 312, 321]
Here is what I tried so far:
>>> import itertools
>>> numbers = [1, 2, 3]
>>> l = list(itertools.permutations(numbers))
>>> print(l)
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
How do I get the output [1, 2, 3, 12, 13, 21, 23, 31, 32, 123, 132, 213, 231, 312, 321]
?
Working code:
import itertools
numbers = [1, 2, 3]
result = []
for n in range(1, len(numbers) + 1):
for x in itertools.permutations(numbers, n): # n - length of each permutation
result.append(int(''.join(map(str, x))))
print(result)
Output:
[1, 2, 3, 12, 13, 21, 23, 31, 32, 123, 132, 213, 231, 312, 321]
I believe the function you are looking at is:
itertools.combinations(iterable, r)
It does the combination of the array iterable in r elements.
So:
>>> import itertools
>>> numbers = [1,2,3]
>>> l = list(itertools.combinations(numbers,2)) # combinations of two
>>> print(l)
[(1, 2), (1, 3), (2, 3)]
You can have more details at the documentation .
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.