Python Itertools 字符串排列

标签 python permutation python-itertools

我想对字符串使用 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')]

关于Python Itertools 字符串排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44449311/

相关文章:

java - 生成所有可能的项目组合

Python根据值列表创建所有字典的组合

python - TKinter tkFileDialog.askopenfilename 总是在其他窗口后面

python - 2018 年 10 月 1 日之前 20 天 ("Pandas")

python - 如何在Python中对排列的每一行求和

python - 复制一个 itertools 循环对象

Python:生成列表的所有有序组合

python - python中的多处理模块和修改共享全局变量

python - 排序()返回无

arrays - 在 VBA 中排列数组以计算 Shapley-Shubik 功率指数