【问题标题】:How to write a Python program which sums up all the given numbers in a date within a given range?如何编写一个 Python 程序来汇总给定范围内的日期中的所有给定数字?
【发布时间】:2022-11-29 14:32:14
【问题描述】:

我编写了一个 Python 程序,它以 yyy-mm-dd 格式打印出 2020 年内的所有日期。现在我尝试编写一个程序,循环/迭代 2020 年并打印出所有给定数字的总和对于每个日期。例如:日期 2020-01-01 的总和为 6(2+0+2+0+0+1+0+1),日期 2020-01-02 的总和为 7,等等。我的问题是我不知道如何编写代码来取出这些数字,将它们相加并打印出 2020 年内的每个日期。

def date_range(start, end):         #creating a tuple function
    for i in range(int((end - start).days)):
        yield start + timedelta(i)

start = date(2020, 1, 1)
end = date(2020, 12, 31)
for each_date in date_range(start, end):
       print(each_date.strftime("%Y-%m-%d") #iterating and printing all dates within the year of 2020

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:
    [int(x) for x in "2020-01-02" if x!='-']
    

    [2, 0, 2, 0, 0, 1, 0, 2]
    

    所以,从那里

    sum([int(x) for x in "2020-01-02" if x!='-'])
    # 7
    

    【讨论】:

      猜你喜欢
      • 2011-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      相关资源
      最近更新 更多