gpt4 book ai didi

python - 如何按周显示数据和周数?

转载 作者:行者123 更新时间:2023-12-04 08:43:40 25 4
gpt4 key购买 nike

我有一个巨大的日期和数字列表,如下所示:

 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
到目前为止,这是我的代码,我已经在他们自己的列表中分隔了日期和数字,但不知道如何从这里开始。
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()
该任务要求我有 0-53 周的时间并使用列表和 strftime %W。

最佳答案

这是完整的代码(代码中作为注释提供的解释):

from datetime import datetime #You messed up with the import statement. It should be from datetime import datetime instead of 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]
datee = datetime.strptime(time, '%d.%m.%Y %H:%M')

if datee.month != 12:
time_list.append(datee.isocalendar()[1])
else:
if datee.isocalendar()[1] == 1:
time_list.append(53)
else:
time_list.append(datee.isocalendar()[1])

electricity_list.append(int(electricity)) #Converts electricity to an integer and appends it to electricity_list

week_numbers = list(set(time_list)) #Removes all repeated week numbers

for week_number in week_numbers: #Iterates over the week_numbers
curr_elec = 0
for week,elec in zip(time_list,electricity_list): #Creates an iterable out of time_list and electricty_list
if week == week_number:
curr_elec += elec #Running total of the electricity for the current week
print(f"{week_number};{curr_elec}")

file.close()

main()
输出:
1;5120
5;1700
6;2340
11;1800
15;2850

关于python - 如何按周显示数据和周数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64439900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com