[英]Count number of occurrences of list of tuples
我需要編寫一個帶有 3 個參數的函數: data
、 year_start
、 year_end
。
data
是元組列表。 year_start
和year_end
是用戶的輸入。
該函數需要計算data
中出現的次數,其中日期范圍內的任何年份都在位置 [0]( data
中的位置 [0] 是年份)。
我需要為該范圍內的每一年以[(year, value), (year, value)]
格式為earthquake_count_by_year = []
total_damage_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(data, 2018, 2020) 的預期輸出:
[(2020, 3), (2019, 0), (2018, 2)]
最終,我需要的其余部分是:causeties_by_year(data, 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.