2016-11-26 59 views
-1

事在厨房

listToPrint = ['pots', 'pans', 'utensils', 'plates', 'cups', 'glasses'] 
while True: 
    newWord = input("Enter a word to add to the list (press return to stop adding words) > ") 
    if newWord == "0": 
     break 
    else: 
     listToPrint.append(newWord) 
+1

当您试图添加“和”列表?这是在所有追加完成后? – roganjosh

回答

0

我想,要构建一个句子以复合主语(单数主语的结合),如“山姆,伯特和我”
比方说,用户只输入字“盘子”
然后,我们可以使用下面的方法(与list.insert()法)简单地构建了最后一句:

listToPrint = ['pots', 'pans', 'utensils', 'plates', 'cups', 'glasses'] 
while True: 
    newWord = input("Enter a word to add to the list (press '0' to stop adding words) > ") 
    if newWord == "0": 
     break 
    else: 
     listToPrint.append(newWord) 

listToPrint.insert(-1, 'and')  # inserts next to last element value 

print(', '.join(listToPrint[:-2]) +' '+ ' '.join(listToPrint[-2:])) 

输出:

pots, pans, utensils, plates, cups, glasses and dishes 
+0

这个清单是献给我的父母,艾因兰德和上帝 –

+0

@WayneWerner,和?他们是否回复了你的名单(信件)? – RomanPerekhrest

+0

下面是我的程序的样子,但是我错过了列表中倒数第二个单词的逗号。谢谢你的帮助.---#listToPrint = ['pots','pans','utensils','plates','cups','glasses'] listToPrint = [] while True: newWord = input (“输入一个单词添加到列表中(按回车停止添加单词)>”) if newWord ==“0”: break listToPrint.append(newWord) listToPrint.insert(-1,'and ') print(','.join(listToPrint [: - 2])+''+''.join(listToPrint [-2:])) –

0

你只需要检查,如果当前项目是最后一个通过列表循环时。

如果是这样,添加 " and " + [current item] 如果没有,添加 ", " + [current item](跳过第一项逗号)

0

[-1]将选择列表中的最后一个成员,或从背后第一,如果你愿意。 另外,如果你想要一个空字符串突破循环,你可以像我一样做。 空字符串返回False

listToPrint = ['pots', 'pans', 'utensils', 'plates', 'cups', 'glasses'] 
while True: 
    newWord = input("Enter a word to add to the list (press return to stop adding words) > ") 
    if not newWord: 
     listToPrint[-1] = 'and ' + listToPrint[-1] 
     break 
    else: 
     listToPrint.append(newWord) 
相关问题