2017-06-09 41 views
0

我想使用字符串而不是字母itertools排列。Python的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’)] 
+1

什麼是您預期的輸出?你原來的想法對我來說看起來不錯,它返回'[]'的原因是因爲你在長度列表中要求長度爲3的排列 - 沒有任何! – maxymoo

+2

它可以很好地排列字符串。但是,您不能從任意順序的兩個列表中選取三個元素。這就是爲什麼你將空列表作爲輸出。 – JohanL

+2

看起來像你想要的[產品](https://docs.python.org/3/library/itertools.html#itertools.product) – Copperfield

回答

2

你可以試試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')] 
+0

如何我得到相同的輸出,如果我的輸入只是['紅','藍色'],我想要同樣的產品? – Silver

+0

@銀牌檢查更新的答案。 –

1

您可以從itertools模塊做到這一點,也與combinations,像這樣的例子:

from itertools import combinations 
final = list(set(combinations(("red","red","blue")*3, 3))) 

print(final) 

輸出:

[('red', 'blue', 'red'), 
('blue', 'red', 'red'), 
('blue', 'blue', 'red'), 
('blue', 'blue', 'blue'), 
('blue', 'red', 'blue'), 
('red', 'blue', 'blue'), 
('red', 'red', 'blue'), 
('red', 'red', 'red')]