[英]How do I add together all numbers from the same week into a list?
I've been googling for answers for about 2 days now and I'm still stuck.我已经在谷歌上搜索了大约 2 天的答案,但我仍然被困住了。
I have a huge list of dates and numbers like this:我有一个巨大的日期和数字列表,如下所示:
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
...
And I need to add all numbers together that have the same week number and return total of numbers in a week like this:我需要将具有相同周数的所有数字加在一起,并返回一周内的总数字,如下所示:
0;0
1;549730
2;645010
3;681320
4;677060
5;698450
...etc
52;576280
53;81640
This is my code so far, I've separated the dates and numbers in their own lists but not sure how to go on from here.到目前为止,这是我的代码,我已经在他们自己的列表中分隔了日期和数字,但不确定如何从这里开始。 I'm supposed to use strftime %W somehow, but don't know how.
我应该以某种方式使用 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()
Just use a simple dictionary and run it sequentially.只需使用一个简单的字典并按顺序运行即可。
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.