微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

计算元组列表的出现次数

如何解决计算元组列表的出现次数

我需要编写一个带有3个参数的函数datayear_startyear_end

data一个元组列表。 year_startyear_end用户的输入。

函数需要计算data中出现的次数,其中日期范围内的任何年份都在位置[0](data中的位置[0]是年份)。>

我需要为该范围内的每一年生成earthquake_count_by_year = []total_damage_by_year = []元组列表,格式为[(year,value),(year,value)]

这就是我所拥有的:

def summary_statistics(data,year_start,year_end):
    earthquake_count_by_year = []
    total_damages_by_year = []
    casualties_by_year = []
    count = 0
    years = []
    year_start = int(year_start)
    year_end = int(year_end)
    
    if year_end >= year_start:
        # store range of years into list
        years = list(range(year_start,year_end+1))
        for index,tuple in enumerate(data):
            if tuple[0] in years:
                count[tuple[0]] += 1
        print(count)

以上只是我尝试计算每年输入中出现的次数。 我觉得如果我能得到这么多,我可以弄清楚其余的东西。

这是data的输入:

[(2020,1,6.0,'CHINA:  XINJIANG PROVINCE',39.831,77.106,2,0),(2020,6.7,'TURKEY:  ELAZIG AND MALATYA PROVINCES',38.39,39.081,41,1600,(2018,7.7,'CUBA: GRANMA;  CAYMAN IS;  JAMAICA',19.44,-78.755,(2019,'TURKEY: VAN;  IRAN',38.482,44.367,10,60,3,5.4,'BALKANS NW:  CROATIA:  ZAGREB',45.897,15.966,27,6000.0),5.7,'USA: UTAH',40.751,-112.078,48.5),7.5,'RUSSIA:  KURIL ISLANDS',48.986,157.693,0)]

list_of_earthquake_count_by_year(数据,2018、2020)的预期输出

[(2020,3),2)]

最终,我需要的其余部分是: Casualties_by_year(数据,2018,2020):

(year,(total_deaths,total_missing,total_injured))

最终以:

L = [[earthquake_count_by_year],[casualties_by_year]]
return L

任何建议都值得赞赏。

解决方法

for item in data:
    if year_start <= item[0] <= year_end:
        # this year is in the range
,

count = 0行将count初始化为整数,但在第count[tuple[0]] += 1行中,您似乎将其视为字典,这是问题的根源。您应该像这样将变量count初始化为字典:

count = {}

现在,由于正在使用字典,因此必须对代码进行较小的更改:

if tuple[0] in years:
    # If the key does not exist in the dictionary,create one
    if tuple[0] not in count:
        count[tuple[0]] = 0

    count[tuple[0]] += 1

所有数据将以以下形式存储在count词典中:

{
    2020: 3,2018: 2,2019: 0
}

现在,您所需要做的就是将数据从字典转换为元组列表,这比这更简单:

list_of_tuples = list(count.items())    # Returns list of tuples
return list_of_tuples

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。