问题
i want to use itertools permutations for strings instead of just letters.
import itertools
lst = list(permutations(("red","blue"),3))
#This returns []
I know i can do something like:
a = list(permutations(range(3),3))
for i in range(len(a)):
a[i] = list(map(lambda x: 'red' if x==0 else 'blue' if x==1 else 'green',a[i]))
EDIT: I want to key in this as my input, and get this as my output
input: ("red","red","blue")
output:
[(’red’, ’red’, ’red’), (’red’, ’red’, ’blue’),\
(’red’, ’blue’, ’red’), (’red’, ’blue’, ’blue’), (’blue’, ’red’, ’red’), \
(’blue’, ’red’, ’blue’), (’blue’, ’blue’, ’red’), (’blue’, ’blue’, ’blue’)]
回答1:
You can try with itertools.product
like this:
import itertools
lst = list(set(itertools.product(("red","red","blue"),repeat=3))) # use set to drop duplicates
lst
lst
will be:
[('red', 'blue', 'red'),
('blue', 'red', 'red'),
('blue', 'blue', 'red'),
('blue', 'blue', 'blue'),
('blue', 'red', 'blue'),
('red', 'blue', 'blue'),
('red', 'red', 'blue'),
('red', 'red', 'red')]
Update:
import itertools
lst = list(itertools.product(("red","blue"),repeat=3))
lst
output:
[('red', 'red', 'red'),
('red', 'red', 'blue'),
('red', 'blue', 'red'),
('red', 'blue', 'blue'),
('blue', 'red', 'red'),
('blue', 'red', 'blue'),
('blue', 'blue', 'red'),
('blue', 'blue', 'blue')]
回答2:
You can do it, also, with combinations
from itertools
module, like this example:
from itertools import combinations
final = list(set(combinations(("red","red","blue")*3, 3)))
print(final)
Output:
[('red', 'blue', 'red'),
('blue', 'red', 'red'),
('blue', 'blue', 'red'),
('blue', 'blue', 'blue'),
('blue', 'red', 'blue'),
('red', 'blue', 'blue'),
('red', 'red', 'blue'),
('red', 'red', 'red')]
来源:https://stackoverflow.com/questions/44449311/python-itertools-permutations-with-strings