【问题标题】:Python adding multiple items to a listPython将多个项目添加到列表中
【发布时间】:2014-11-16 19:34:32
【问题描述】:

我必须编写一个程序,要求用户输入他们的购物清单,它应该要求他们输入他们的第一个项目,并在他们输入所有项目后输入“END”。

这是我目前的代码:

#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)

我不确定如何解决第二次添加到列表的问题,您能帮忙吗?谢谢。

【问题讨论】:

    标签: python list python-3.x append


    【解决方案1】:

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

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

    [:-1] 是删除END。或者你可以把它变成一个过滤器

    shoppingList = [item for item in input(print("....")).split() if item != 'END']
    

    【讨论】:

    • 如果我使用任何一种方法,每个字符都是单独打印的,即牛奶变成'm','i','l','k'。有没有什么办法解决这一问题?谢谢
    • @barry 这行不通,至于先遍历输入字符串
    • 是的,抱歉,忘记添加.split()
    【解决方案2】:

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

    shoppingList.append("Bread")
    

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

    while True:
        new_item = input(print("Please enter an item of your shopping list and type END when you have entered all of your items: "))
        if new_item == "END": break
        shoppingList.append(new_item)
    

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

    【讨论】:

      【解决方案3】:

      添加 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循环。
      变量item 将存储用户输入并将其附加到shopingList,end 变量与用户项目一样更新,而end 变量与字符串'end'进行比较

      【讨论】:

      • 嗨,谢谢,我对python比较陌生,有没有更简单的方法?
      • 我刚刚重试了,我一定是打错了,现在可以了。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-28
      相关资源
      最近更新 更多