我想对字符串使用 itertools 排列而不仅仅是字母。
import itertools
lst = list(permutations(("red","blue"),3))
#This returns []
我知道我可以做类似的事情:
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]))
编辑: 我想输入这个作为我的输入,然后得到这个作为我的输出
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’)]
请您参考如下方法:
您可以像这样尝试使用 itertools.product:
import itertools
lst = list(set(itertools.product(("red","red","blue"),repeat=3))) # use set to drop duplicates
lst
lst 将是:
[('red', 'blue', 'red'),
('blue', 'red', 'red'),
('blue', 'blue', 'red'),
('blue', 'blue', 'blue'),
('blue', 'red', 'blue'),
('red', 'blue', 'blue'),
('red', 'red', 'blue'),
('red', 'red', 'red')]
更新:
import itertools
lst = list(itertools.product(("red","blue"),repeat=3))
lst
输出:
[('red', 'red', 'red'),
('red', 'red', 'blue'),
('red', 'blue', 'red'),
('red', 'blue', 'blue'),
('blue', 'red', 'red'),
('blue', 'red', 'blue'),
('blue', 'blue', 'red'),
('blue', 'blue', 'blue')]
