带有字符串的Python Itertools排列 [英] Python Itertools permutations with strings
本文介绍了带有字符串的Python Itertools排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对字符串使用itertools排列,而不仅仅是字母.
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]))
我想输入它作为输入,并得到它作为输出
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’)]
推荐答案
您可以像这样尝试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')]
这篇关于带有字符串的Python Itertools排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文