【问题标题】:Selecting elements in list Python在列表 Python 中选择元素
【发布时间】:2014-10-26 17:10:41
【问题描述】:

我正在尝试在包含每月天数的列表中选择元素,并将这些天数添加到包含总计的变量中。

from datetime import date
months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
inmonth = str(float(input("month")))
intmonth = int(inmonth[0])
nowmonth = (date.today().month)
days = 0

if intmonth < nowmonth:
    for c in range(months[intmonth-1], months[nowmonth-1]):
        days = days + months[c]
print(days)

编辑:

好的,我解决了输入的问题,但是这段代码没有添加任何内容,有什么想法吗?

谢谢。

【问题讨论】:

  • 试试months[int('03')]
  • 您要计算两个日期之间的天数吗?
  • 试试这个:days = days + monthsrev[int(c)]
  • 是的,如果输入的年份大于当前年份,这只是代码的 sn-p。我没有使用 date(a)-date(b) 函数。
  • @user2975192:请写下您找到的解决方案并接受它。许多其他人也会遇到类似的问题,如果每个满意的客户都无影无踪地离开,那么 SO 就不会存在

标签: python list date


【解决方案1】:

除了 Kieleth 所述的问题之外,您的循环没有使用您期望的索引。 我们现在是 10 月 (nowmonth = 10),假设我在 4 月回答 4

for c in range(months[intmonth-1], months[nowmonth-1]):

给出intmonth-1 = 3, months[intmonth-1] = 30, nowmonth-1 = 9, months[nowmonth-1] = 31 => c 得到值30 !!!

所以你的代码应该是:

from datetime import date
months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
intmonth = int(input("month")) # fixes the problem stated by Kieleth
nowmonth = (date.today().month)
days = 0

if intmonth < nowmonth:
    for c in range(intmonth-1, nowmonth-1):
        days = days + months[c]
print(days)

但是如果很简单,找到这些类型或错误的方法:print 是你的朋友 !!!

如果你只是写了:

from datetime import date
months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
inmonth = str(float(input("month")))
intmonth = int(inmonth[0])
print(inmonth, intmonth) # control input
nowmonth = (date.today().month)
days = 0

if intmonth < nowmonth:
    for c in range(months[intmonth-1], months[nowmonth-1]):
        print (c, days) # a spy per iteration
        days = days + months[c]
print(days)

很明显你没有通过循环

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 2020-08-01
    相关资源
    最近更新 更多