簡體   English   中英

如何在最后一個元素之前添加一個元素?

[英]How do I add an element to right before the last element?

如果提示允許用戶將多個項目添加到列表中,我無法弄清楚如何索引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)

正如@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']

我希望我能正確理解這個問題。 如果沒有,請原諒我。 所以,[-1] 將索引序列的最后一個元素,我相信。 因此 [-2] 將指示倒數第二個元素。

本質上,這應該使用:

listLen = len(listToPrint)
if listLen > 1:
    listToPrint.insert(listLen - 1, "and")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM