【问题标题】:Checking two lists of tuples for same first value检查两个元组列表是否具有相同的第一个值
【发布时间】:2016-11-30 11:41:15
【问题描述】:

如何检查两个元组列表是否具有相同的第一个值?

list1=[(1,3),(3,2),(5,-5),(7,7)]
list2=[(1,-2),(2,2),(4,8),(5,6)]

我要加list1[i][1] to list2[y][1] if list1[i][0] is = list2[y][0]

所以对于示例列表,

(1,3) and (1,-2)
and
(5,-5) and (5,6)

应该加上 3+(-2) 和 -5+6

【问题讨论】:

    标签: python-2.7 list tuples


    【解决方案1】:

    您似乎正在尝试重新发明字典,那么为什么不直接使用它们呢?这将大大缩短查找时间

    dict1 = dict(list1)
    dict2 = dict(list2)
    
    result = {k1: v1 + dict2.get(k1, 0) for k1, v1 in dict1.iteritems()}
    

    但如果你真的想使用列表:

    for i, (i0, i1) in enumerate(list1):
        for y0, y1 in list2:
            if i0 == y0:
                list1[i][1] += y1
    

    【讨论】:

    • 遇到错误 TypeError: 'tuple' object does not support item assignmentworks,但其他方面工作得很好,谢谢
    猜你喜欢
    • 1970-01-01
    • 2019-05-16
    • 2014-02-03
    • 2017-03-25
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    相关资源
    最近更新 更多