繁体   English   中英

将元组的值加在一起

[英]Adding the values of tuples together

class WaitingList:
       
    def __init__(self):
           
        self.items = []   
     
    
    def stillWaiting(self, destination):
        newList = []
        index  = 0
        for i in range(0, len(self.items)):
            thisGroup = self.items[index]
            if thisGroup[1] == thisGroup[1]:
                duplicates = thisGroup[0] + thisGroup[0]
                newList = duplicates
            else:
                newList = i
    return newList

self.items 存储一个元组列表,例如

self.items = [(3,"Rome"),(2,"Naples"),(1,"Pisa"), (1,"Florence"), (25,"Rome")]

我要求我的程序遍历任何给定列表中的每个元组,如果目的地(即罗马)在任何元组中都是常见的,则添加出现在元组中目的地旁边的数字并将结果存储在新列表中。 所以上面的预期结果是:

[28,"Rome"), (2,"Naples"),(1,"Pisa"), (1,"Florence")]

谢谢

from collections import defaultdict

city_to_num = defaultdict(int)
for num, city in self.items:
    city_to_num[city] += num

output = [(num, city) for city, num in city_to_num.items()]

看起来你正在做某种频率的事情。 所以不要将此作为答案,但为什么不改变 self.items 的工作方式。 创建一个具有名称和值的元组似乎有点幼稚,为什么不创建一个字典并使用 setdefault 或 get 之类的东西,这样一开始就不会在 dict 中有重复项,如果必须的话,你甚至可以转换使用 items() 字典到元组列表

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM