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

List of tuples from (a, all b) to (b, all a)

我从元组列表 (a,all 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 执行此操作?感谢您的帮助。

您可以使用 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'])]

我会做类似的事情

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())

整理版,自娱自乐:

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']),
]))