'列表索引必须是整数,而不是元组'使用sep =' \ n'时出错

时间:2014-12-10 18:50:59

标签: python list

我制作了一个快速程序,以尽可能少的行输出'圣诞节12天'的完整脚本。

但是在使用时:

print(myList,sep='\n')

在完整的计划中:

script = ["st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "A patridge in a pear tree", "Two turtle doves and", "Three french hens", "Four calling birds", "Five golden rings", "Six geese a laying", "Seven swans are swimming", "Eight maids are milking", "Nine ladies dancing", "Ten lords-a-leaping", "Elven pipers piping", "Twelve drummers drumming"]
for each in range(1,13):
    print(("On the ") + str(each) + str(script[each - 1]) + " day of christmas my true love gave to me")
    print(script[11 , (each) + 10] ,sep='\n')

我收到错误消息:

print(script [11,(each)+ 10],sep ='\ n')

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

我在网上看过但似乎没什么好看的,我现在正撞在墙上。无论如何感谢阅读。

1 个答案:

答案 0 :(得分:2)

通过在表达式script中将逗号放入索引script[11 , (each) + 10],您尝试将元组(11, each+10)作为索引,这对列表没有意义。

如果要在两个索引之间打印元素,则需要使用切片,该切片使用冒号而不是逗号。例如,script[2:5]将打印索引2到5的元素(包括2但不是5)。

但是,要获得正确的歌词,您需要的是在向后顺序中将元素从each+11打印到11:

print(*script[(each) + 11:11:-1] ,sep='\n')

这给出了正确的结果:

On the 1st day of christmas my true love gave to me
A patridge in a pear tree
On the 2nd day of christmas my true love gave to me
Two turtle doves and
A patridge in a pear tree
On the 3rd day of christmas my true love gave to me
Three french hens
Two turtle doves and
A patridge in a pear tree
[etc.]