如何在列表中置换元组。
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 :(得分: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)
生成器表达式为product()
生成3个参数,每个参数都包含一个子列表和A
子列表的反转:
>>> [(l, l[::-1]) for l in A]
[(('a', 'b'), ('b', 'a')), (('c', 'd'), ('d', 'c')), (('e', 'f'), ('f', 'e'))]
答案 1 :(得分: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).