2013-09-27 52 views
0

如何排列列表上的元組。生成列表中的排列元組列表

A= [(a,b), (c,d), (e, f)] 

如果A是一個列表,然後用置換元組,該列表是

[(a,b), (c,d), (e, f)] 
    [(a,b), (c,d), (f, e)] 
    [(a,b), (d,c), (e, f)] 
    [(a,b), (d,e), (f, e)] 
    .... 

它有8個這樣的列表。

+0

你可能想使你沒有使用通常的排列本身這一點更加明顯在這裏;你想創建'A'的常規和倒置子列表的* product *。 –

回答

5

使用itertools.product()與發電機表達以產生倒置:

>>> from itertools import product 
>>> A = [('a', 'b'), ('c', 'd'), ('e', 'f')] 
>>> for perm in product(*((l, l[::-1]) for l in A)): 
...  print perm 
... 
(('a', 'b'), ('c', 'd'), ('e', 'f')) 
(('a', 'b'), ('c', 'd'), ('f', 'e')) 
(('a', 'b'), ('d', 'c'), ('e', 'f')) 
(('a', 'b'), ('d', 'c'), ('f', 'e')) 
(('b', 'a'), ('c', 'd'), ('e', 'f')) 
(('b', 'a'), ('c', 'd'), ('f', 'e')) 
(('b', 'a'), ('d', 'c'), ('e', 'f')) 
(('b', 'a'), ('d', 'c'), ('f', 'e')) 

((l, l[::-1]) for l in A)發生器表達產生3個參數來product(),每個由兩個子列表和A該子列表的反轉的元組:

>>> [(l, l[::-1]) for l in A] 
[(('a', 'b'), ('b', 'a')), (('c', 'd'), ('d', 'c')), (('e', 'f'), ('f', 'e'))] 
+0

好吧...感謝代碼:) –

1
from itertools import chain, permutations 

A = [('a', 'b'), ('c', 'd'), ('e', 'f')] 

print map(lambda x: zip(*[iter(x)]*2),permutations(chain(*A))) 

# Hints: 
# chain(*A) => ['a', 'b', 'c', 'd', 'e', 'f'] 

# permutations(chain(*A)) => ('a', 'b', 'c', 'd', 'e', 'f'), 

#       ('a', 'b', 'c', 'd', 'f', 'e'), 

#       ('a', 'b', 'c', 'e', 'd', 'f'), 
          ... 
# lambda x: zip(*[iter(x)]*2) chunks the iterable by length 2 

# [iter(x)]*2 creates a list contains 2 references to a same iterator object. 

# The left-to-right evaluation order of the iterables is guaranteed.     
# This makes possible an idiom for clustering a data series 
# into n-lengthgroups using zip(*[iter(s)]*n).