如何将同一周的所有数字加到一个列表中? [英] How do I add together all numbers from the same week into a list?

查看:71
本文介绍了如何将同一周的所有数字加到一个列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜寻了大约2天的答案,但我仍然被困住.

I've been googling for answers for about 2 days now and I'm still stuck.

我有很多这样的日期和数字列表:

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

到目前为止,这是我的代码,我已经将日期和数字分隔在自己的列表中,但不确定如何从此处继续.我应该以某种方式使用strftime%W,但不知道如何使用.

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.

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}")

这篇关于如何将同一周的所有数字加到一个列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆