【问题标题】:List of tuples from (a, all b) to (b, all a)从 (a, all b) 到 (b, all a) 的元组列表
【发布时间】:2015-06-22 20:06:36
【问题描述】:

我从一个元组列表开始(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 做到这一点?感谢您的帮助。

【问题讨论】:

  • 我不明白你是如何得出这个输出的,你能进一步解释一下吗?另外,到目前为止,您尝试过什么?你具体卡在哪里了?
  • 使用defaultdictdict.setdefault 方法

标签: python list python-2.7 tuples


【解决方案1】:

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

【讨论】:

  • 看起来你比我早了 22 秒(并且有一个实际的例子可以引导...... +1 先生!)
【解决方案2】:

我会做类似的事情

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

【讨论】:

    【解决方案3】:

    一个排序版本,为了好玩:

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

    【讨论】:

      猜你喜欢
      • 2020-11-22
      • 2020-07-08
      • 1970-01-01
      • 2020-07-15
      • 2021-02-18
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 2014-03-29
      相关资源
      最近更新 更多