计算元组列表的出现次数

Count number of occurrences of list of tuples

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

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

函数需要统计data中出现的次数,其中日期范围内的任意年份在位置[0](data中的位置[0]为年份)。

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

这是我的:

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

list_of_earthquake_count_by_year(数据,2018 年、2020 年)的预期产出:

[(2020, 3), (2019, 0), (2018, 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 = 0count 初始化为整数,但在行 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