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

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 に答える