[英]How do I add together all numbers from the same week into a list?
我已經在谷歌上搜索了大約 2 天的答案,但我仍然被困住了。
我有一個巨大的日期和數字列表,如下所示:
1.1.2018 0:00;2590
3.1.2018 1:00;2530
4.2.2018 2:00;1700
6.2.2018 3:00;2340
18.3.2018 4:00;1800
15.4.2018 5:00;2850
...
我需要將具有相同周數的所有數字加在一起,並返回一周內的總數字,如下所示:
0;0
1;549730
2;645010
3;681320
4;677060
5;698450
...etc
52;576280
53;81640
到目前為止,這是我的代碼,我已經在他們自己的列表中分隔了日期和數字,但不確定如何從這里開始。 我應該以某種方式使用 strftime %W ,但不知道如何使用。
import datetime
from datetime import date
from datetime import datetime
def main():
file = open("2018Electricity.txt", "r")
line = file.readline()
time_list = []
electricity_list = []
total = []
for i in file:
time = i.strip().split(';')[0]
electricity = i.strip().split(';')[1]
time_list.append(datetime.strptime(time, '%d.%m.%Y %H:%M'))
electricity_list.append(electricity)
file.close()
main()
只需使用一個簡單的字典並按順序運行即可。
import datetime
def solution():
data = [
"1.1.2018 0:00;2590",
"3.1.2018 1:00;2530",
"4.2.2018 2:00;170",
"6.2.2018 3:00;2340",
"18.3.2018 4:00;1800",
"15.4.2018 5:00;2850"
]
result = {} # store in a dictionary
for date in data:
day = int(date.split(".")[0])
month = int(date.split(".")[1])
year = int(date.split(".")[2][0:5])
week = datetime.date(year, month, day).isocalendar()[1]
if week not in result:
result[week] = 0
result[week] += int(date.split(";")[1])
return result
result = solution()
for week, value in result.items():
print(f"{week};{value}")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.