Python向列表添加多个项目

2024-06-16 11:51:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须写一个程序,要求用户输入他们的购物清单,它应该要求他们输入他们的第一个项目,并输入'结束'当他们已经输入他们的所有项目。在

这是我目前为止的代码:

#Welcome
name = input("What is your name? ")
print("Welcome %s to your shopping list" %name)
#Adding to the list
shoppingList = []
shoppingList.append = input(print("Please enter the first item of your shopping list and type END when you have entered all of your items: "))
length = len(shoppingList)
#Output
print("Your shopping list is", length, "items long")
shoppingList.sort
print(shoppingList)

我不知道该怎么解决第二次加入名单的问题,你能帮忙吗?谢谢。在


Tags: oftheto项目nameinputyouris
3条回答

您正在分配给append方法。您要做的是分配给实际列表:

shoppingList = [item for item in input(print("....")).split()][:-1]

那里的[:-1]要删除{}。或者你可以做个过滤器

^{pr2}$

添加while并检查End

shopingList = []
end =''
while end.lower() != 'end':
    item = input("Please enter the item of youi shopping list and type END when you have entered all of your items: ")
    shopingList.append(item)
    end = item

input内不需要print语句

在上面的代码中,我检查用户是否输入end它将来自while循环。
varible item将存储用户输入并将其附加到shoppinglist,end变量与字符串'end'比较时,end变量与用户项一起更新

Append是一个函数,所以应该像这样调用它。在

shoppingList.append("Bread")

但是,为了添加多个项,需要某种循环。在

^{pr2}$

此循环将每个非“END”的字符串追加到列表中。当输入“END”时,循环结束。在

相关问题 更多 >