[英]'List indices must be integers, not tuple' Error when using sep='\n'
我編寫了一個快速程序,以最少的行數輸出了“聖誕節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')
我收到以下錯誤消息:
打印(腳本[11 [(每個)+ 10],sep ='\\ n')
TypeError:列表索引必須是整數,而不是元組
我在網上看過,但是似乎什么都不合適,現在我把頭撞在牆上。 無論如何,感謝您的閱讀。
通過將一個逗號索引里面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.]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.