【问题标题】:Count elements in pair of tuples [closed]计算一对元组中的元素[关闭]
【发布时间】:2022-01-02 21:40:38
【问题描述】:

我有一个元组列表

[(6, 0, 16), (6, 0, 76)]
[(6, 0, 86), (6, 0, 91)]
[(6, 2, 96), (6, 2, 97)]
[(6, 3, 3), (6, 3, 17)]
[(6, 4, 2), (6, 4, 41)]
[(10, 1, 47), (10, 1, 64)]
[(10, 2, 21), (10, 2, 35)]
[(10, 2, 48), (10, 2, 77)]
[(10, 4, 75), (10, 4, 76)]
[(15, 3, 35), (15, 3, 36)]
[(15, 3, 45), (15, 3, 61)]
[(15, 4, 50), (15, 4, 58)]

并且希望我的输出是一个字典,计算一对中第一个元组的第一个元素

输出应如下所示:

{6: 5, 10: 4, 15: 3}

【问题讨论】:

  • 列表存储在哪种数据结构中?现在,它们只是漂浮在周围
  • 告诉我们您的尝试,以便我们为您提供帮助。

标签: python list dictionary duplicates tuples


【解决方案1】:

假设您有一个三元组列表。

解决办法是:

from collections import Counter

lst = [
    [(6, 0, 16), (6, 0, 76)],
    [(6, 0, 86), (6, 0, 91)],
    [(6, 2, 96), (6, 2, 97)],
    [(6, 3, 3), (6, 3, 17)],
    [(6, 4, 2), (6, 4, 41)],
    [(10, 1, 47), (10, 1, 64)],
    [(10, 2, 21), (10, 2, 35)],
    [(10, 2, 48), (10, 2, 77)],
    [(10, 4, 75), (10, 4, 76)],
    [(15, 3, 35), (15, 3, 36)],
    [(15, 3, 45), (15, 3, 61)],
    [(15, 4, 50), (15, 4, 58)],
]

print(dict(Counter([elt[0][0] for elt in lst])))

输出:

{6: 5, 10: 4, 15: 3}

【讨论】:

    【解决方案2】:
    from collections import defaultdict
    
    input = [[(6, 0, 16), (6, 0, 76)],
    [(6, 0, 86), (6, 0, 91)],
    [(6, 2, 96), (6, 2, 97)],
    [(6, 3, 3), (6, 3, 17)],
    [(6, 4, 2), (6, 4, 41)],
    [(10, 1, 47), (10, 1, 64)],
    [(10, 2, 21), (10, 2, 35)],
    [(10, 2, 48), (10, 2, 77)],
    [(10, 4, 75), (10, 4, 76)],
    [(15, 3, 35), (15, 3, 36)],
    [(15, 3, 45), (15, 3, 61)],
    [(15, 4, 50), (15, 4, 58)]]
    
    #  counts my first element of the first tuple within a pair
    # result: {6: 5, 10: 4, 15: 3}
    
    count = defaultdict(int)
    for item in input:
        count[item[0][0]] += 1
    
    print(dict(count))
        
    
    

    结果:

    {6: 5, 10: 4, 15: 3}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多