简体   繁体   English

带有字符串的Python Itertools排列

[英]Python Itertools permutations with strings

i want to use itertools permutations for strings instead of just letters. 我想对字符串使用itertools排列,而不仅仅是字母。

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’)]

You can try with itertools.product like this: 您可以像这样尝试itertools.product

import itertools
lst = list(set(itertools.product(("red","red","blue"),repeat=3))) # use set to drop duplicates
lst

lst will be: 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')]

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')]

You can do it, also, with combinations from itertools module, like this example: 您也可以使用itertools模块的combinations来完成此操作,例如以下示例:

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')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM