从(a,all b)到(b,all a)的元组列表

时间:2015-06-22 20:06:36

标签: python list python-2.7 tuples

我从一个元组列表开始(a,所有b)。我想以元组列表结束(b,all a)。

例如:

FROM  
(a1,[b1,b2,b3])  
(a2,[b2])  
(a3,[b1,b2])

TO  
(b1,[a1,a3])  
(b2[a1,a2,a3])  
(b3,[a1]

如何使用Python 2执行此操作?谢谢你的帮助。

3 个答案:

答案 0 :(得分:5)

您可以使用collections.defaultdict

tups = [
    ('a1',['b1','b2','b3']),
    ('a2',['b2']),
    ('a3',['b1','b2'])
]

d = collections.defaultdict(list)
for a, bs in tups:
    for b in bs:
        d[b].append(a)

然后:

>>> d.items()
[('b1', ['a1', 'a3']), ('b2', ['a1', 'a2', 'a3']), ('b3', ['a1'])]

答案 1 :(得分:0)

我会做像

这样的事情
from collections import defaultdict

output = defaultdict(list)

for a, b_s in input:
    for b in b_s:
        output[b].append(a)

# to put back to tuples:

output = tuple(output.items())

答案 2 :(得分:0)

排序版本,为了好玩:

import itertools
import operator

# Function to get first element of a tuple
fst = operator.itemgetter(0)


def invert(items):
    # (b, a) pairs, sorted by b
    pairs = sorted((b, a) for a, bs in items for b in bs)

    # (b, [(b, a)]) groups
    groups = itertools.groupby(pairs, key=fst)

    # (b, [a]) groups
    return [(b, [a for (_, a) in items]) for b, items in groups]


print(invert([
    ('a1', ['b1', 'b2', 'b3']),
    ('a2', ['b2']),
    ('a3', ['b1', 'b2']),
]))