计算元组列表的出现次数



我需要编写一个函数,它需要 3 个参数:datayear_startyear_end

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

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

我需要生成earthquake_count_by_year = []元组列表,并以该范围内每年[(year, value), (year, value)]的格式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 = 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

最新更新