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 个这样的列表。

4

2 回答 2

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'))]
于 2013-09-27T08:41:43.697 回答
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).
于 2013-09-27T09:30:25.030 回答