【问题标题】:Error "list indices must be integers or slices, not tuple" occurs when I try to use function parametrs as list indices当我尝试使用函数参数作为列表索引时,出现错误“列表索引必须是整数或切片,而不是元组”
【发布时间】:2019-11-24 17:07:20
【问题描述】:

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

TypeError:列表索引必须是整数或切片,而不是元组。

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))

【问题讨论】:

  • 欢迎来到 Stack Overflow!查看tour
  • 您期待列表中的一部分吗?为此尝试gifts[end_verse-1::-1]

标签: python python-3.x list


【解决方案1】:

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

您应该只使用整数值。也许您的意思是以下选项之一:

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

【讨论】:

  • end_verse-1不是比-1+end_verse更清晰吗?
  • 是的。当然。这只是我写的一个选项,但使用 end_verse - 1 更清晰
【解决方案2】:

我认为这个gifts[-1, end_verse] 是问题所在。您不能将元组作为列表索引。也许你想在这里gifts[end_verse-1]

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))

【讨论】:

    【解决方案3】:

    recite 函数中的 return 语句不正确。下面的代码可能是您想要的。这是假设 recite(1,1) 用于第一天,recite(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])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 2019-09-15
      • 1970-01-01
      • 2022-01-16
      相关资源
      最近更新 更多