list.insert如果提示允許用戶將多個專案添加到串列中,我無法弄清楚如何建立索引。我需要在"and"列出的最后一項之前添加。
listToPrint = []
while True:
newWord = input("Enter a word to add to the list (press return to stop adding words) > ")
if newWord == "":
break
else:
listToPrint.append(newWord)
print(listToPrint)
uj5u.com熱心網友回復:
正如@christiandean 在評論中建議的那樣,這就是你所追求的:
listToPrint = []
while True:
newWord = input("Enter a word to add to the list (press return to stop adding words) > ")
if newWord == "":
break
else:
listToPrint.append(newWord)
listToPrint.insert(len(listToPrint)-1, "and")
print(listToPrint)
但是,如果沒有輸入任何單詞,則會失敗,所以這樣更安全:
listToPrint = []
while True:
newWord = input("Enter a word to add to the list (press return to stop adding words) > ")
if newWord == "":
break
else:
listToPrint.append(newWord)
if len(listToPrint) > 1:
listToPrint.insert(len(listToPrint)-1, "and")
print(listToPrint)
輸出:
Enter a word to add to the list (press return to stop adding words) > this
Enter a word to add to the list (press return to stop adding words) > that
Enter a word to add to the list (press return to stop adding words) > more
Enter a word to add to the list (press return to stop adding words) >
['this', 'that', 'and', 'more']
uj5u.com熱心網友回復:
我希望我能正確理解這個問題。如果沒有,請原諒我。所以,[-1] 將索引序列的最后一個元素,我相信。因此 [-2] 將指示倒數第二個元素。
uj5u.com熱心網友回復:
本質上,這應該使用:
listLen = len(listToPrint)
if listLen > 1:
listToPrint.insert(listLen - 1, "and")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/491956.html
