python - 它有效,但为什么需要通过减去 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是零索引的。这意味着第一个元素是0
而不是1
例如:
在您的代码中,用户将三月指定为 3(1 月 1 日、2 月 2 日、3 月 3 日)
但是在您的 python 列表中,三月将排在第二位(1 月 0 日、2 月 1 日、3 月 3 日)
大多数编码语言都是 0 索引的,对于 python,所有可迭代的东西也是 0 索引
推荐阅读
- javascript - 将数组元素传递给另一个组件
- javascript - 无法在 android (RN 0.64.2) 中加载新项目的脚本
- python - Py Click (8.0) flag_value 被转换为 str
- linkedin - 如何在linkedin营销api中获得r_ads_leadgen_automation权限
- sql - 使用 Case (Teradata) 的 SQL 窗口
- javascript - 从 getBoundingClientRect() 设置边距
- .net - 在 WebAPI 中使用 autofac 在运行时创建的对象中解析每个请求服务
- javascript - 使用覆盖在 ESLint 配置中设置文件扩展名
- machine-learning - Pytorch 自定义模型自动存储在 cuda 中
- linq - .NET Core 的 SQL 转换为 Linq 转换