首页 > 解决方案 > 它有效,但为什么需要通过减去 1 来更改索引

问题描述

新手,问题,为什么我需要减去一个来引用month_name 和ordinal 的正确索引。

这会打印出日期,给定年、月和日作为输入的数字。

months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 
          'August', 'September', 'October', 'November', 'December']

endings = ['st', 'nd', 'rd'] + 17 * ['th'] \
        + ['st', 'nd', 'rd'] + 7 * ['th'] \
        + ['st']

year = input('Year: ')

month = input('Month (1-12: ')

day = input('Day (1-31): ')

month_number = int(month) 

day_number = int(day)    

month_name = months[month_number-1]  #Although it works, what's the logic.
ordinal = day + endings[day_number-1 #Although it works, what's the  logic.

print(month_name , ' ' + ordinal , ', ' + year)

标签: python

解决方案


因为python是零索引的。这意味着第一个元素是0而不是1

例如:

在您的代码中,用户将三月指定为 3(​​1 月 1 日、2 月 2 日、3 月 3 日)

但是在您的 python 列表中,三月将排在第二位(1 月 0 日、2 月 1 日、3 月 3 日)

大多数编码语言都是 0 索引的,对于 python,所有可迭代的东西也是 0 索引


推荐阅读