当我尝试使用函数parametrs作为列表索引时,出现错误“列表索引必须是整数或片,而不是元组”

2024-04-19 10:26:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用函数的参数作为索引列表,但是

TypeError: list indices must be integers or slices, not a tuple.

days=['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh']

gifts=['and a patriage in a Pear tree', 'two Turtle Doves', 'three French Hens', 'four Calling Birds', 'five Gold Rings', 'six Geese-a-Laying', 'seven Swans-a-Swimming', 'eigth Maids-a-Milking', 'nine Ladies Dancing', 'ten Lords-a-Leaping', ' eleven Pipers Piping', 'twelve Drummers Drumming']

def recite( start_verse, end_verse):
    return ('On the '+days[start_verse+1] + ' day of Christmas my true love gave to me: '+ gifts[-1, end_verse])

print(recite(2,2))

Tags: integers函数列表参数bedaysstartlist
3条回答

我认为这就是问题所在。不能将元组作为列表索引。也许你想要这里

days=['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh']


gifts=['and a patriage in a Pear tree', 'two Turtle Doves', 'three French Hens', 'four Calling Birds', 'five Gold Rings', 'six Geese-a-Laying', 'seven Swans-a-Swimming', 'eigth Maids-a-Milking', 'nine Ladies Dancing', 'ten Lords-a-Leaping', ' eleven Pipers Piping', 'twelve Drummers Drumming']

def recite(start_verse, end_verse):
    return 'On the '+ str(days[start_verse+1]) + ' day of Christmas my true love gave to me: '+ str(gifts[end_verse-1])

print(recite(2,2))

您的return语句在read函数中不正确。下面的代码可能就是您想要的。这是假设背诵(1,1)是第一天,背诵(2,2)是第二天,依此类推

def recite(start_verse, end_verse):
   days=['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth']
   gifts=['and a patriage in a Pear tree', 'two Turtle Doves', 'three French Hens', 'four Calling Birds', 'five Gold Rings', 'six Geese-a-Laying', 'seven Swans-a-Swimming', 'eigth Maids-a-Milking', 'nine Ladies Dancing', 'ten Lords-a-Leaping', ' eleven Pipers Piping', 'twelve Drummers Drumming']
   return("On the " + days[start_verse-1] + " day of Christmas my true love gave to me: " + gifts[end_verse-1])

问题就在这里gifts[-1, end_verse]。 您正在使用元组作为索引

应该只使用整数值。也许你指的是这些选项之一:

gifts[-1 + end_verse]
gifts[end_verse - 1]
gifts[-1]
gifts[end_verse]

相关问题 更多 >