如何访问元组中的指示项而不是全部

时间:2017-08-27 19:59:02

标签: python tuples

所以我正在尝试编写代码来将输入的整数更改为一个月。目标是获取输入的参数并将其转换为日期。代码如下。

def date(month, day, year):
    mon = ("January", "February", "March", "April", "May", "June", "July", 
     "August", "September", "October", "November", "December")
    for i in range(len(mon)):
        print(mon[i]+" "+str(day)+", "+str(year))

使用此代码,我可以让它以正确的格式打印1月到12月的所有日期,但我不知道要改变什么

for i in range(len(mon)):

以便仅选择在参数中输入的月份。

EX:当我date(6,17,2016)进入控制台时,它应该打印June 17, 2016

1 个答案:

答案 0 :(得分:3)

您需要删除for循环并按索引访问mon元组,例如:

def date(month, day, year):
    mon = ("January", "February", "March", "April", "May", "June", "July", 
     "August", "September", "October", "November", "December")
    print('{} {}, {}'.format(mon[month-1], day, year))

由于元组索引从0开始,您可以使用month-1每月访问一次

1 - 1 = 0 代表January,因为mon[0]January