Skip to main content
 首页 » 编程设计

Python将元组压缩为第一个值

2025年05月04日13birdshome

我有一个输出的元组列表

[('city 1', '#' ), ('city 1', '#' ), ('city 2', '#' ), ('city 2', '#'), etc...]  

我需要做的是将每个城市的所有 # 值相加并输出一个列表:

[('city 1', 'sumof#' ), ('city 2', 'sumof#' ), ('city 3', 'sumof#' ), ('city 4', 'sumof#'), etc...] 

请您参考如下方法:

不确定你想要什么。可能是这个?:

>>> d = [('city 1', 2 ), ('city 1', 1 ), ('city 2', 2 ), ('city 2', 4)] 
# Have an empty dictionary to calculate and store result 
>>> r = {} 
# Iterate through the list 
# As the list contains tuples with 2 elements, we can just  
# make use of unpacking 
>>> for city,count in d: 
        # dict.setdefault will try to get the city count, but 
        # if not exists (first time) it will return the provided 
        # default value; 0 here. Just add up. 
        r[city] = r.setdefault(city,0) + count 
 
# items() contains the key-value pair. May be this is the result?        
>>> r.items() 
[('city 2', 6), ('city 1', 3)]