如何允许用户将单个列表项输入到列表列表中?

时间:2019-01-09 07:45:47

标签: python python-3.x

我正在尝试以最简单的方式创建记录,以允许用户将项目输入到存储在更大列表列表中的列表中,当手动编码时一切正常,只是不作为在输入提示时运行来自用户

myitems = [[1,"Item1",100,0],[2,"Item2",150,0],[3,"Item3",75,0],[4,"Item4",20,0],[5,"Item5",15,0]]

def printall():
    for x in myitems: 
        print (x[0],x[1],x[2],x[3],x[4],x[5],x[6])

def new():
    userinput = input("New?:")
    if userinput == "y":
        userinput = int(input("Please enter a number:"))
        myitems.append(userinput[0])
        userinput = input("Please enter a name:")
        myitems.append(userinput[1])

如您所见,我直接编写了5条记录,我试图让用户将新记录追加到myitems上,但是我不知道如何允许他们将单个项目追加到列表中,然后让它们存储与其他列表一起存储

4 个答案:

答案 0 :(得分:2)

从原始问题的注释中移出:

myitems = [[1,"Item1",100,0],[2,"Item2",150,0],[3,"Item3",75,0],[4,"Item4",20,0],[5,"Item5",15,0]]
tempList = []

# Function print_all

def printall():
    for x in myitems:
        print(*x)       

# Function new()

def new():
    userinput = int(input("Please enter a number:"))
    tempList.append(userinput)

    userinput = input("Please enter a name:")
    tempList.append(userinput)

    myitems.append(tempList[:])
    tempList.clear()
    printall()

# Calling the function
new()

输出:

Please enter a number:6
Please enter a name:item6
1 Item1 100 0
2 Item2 150 0
3 Item3 75 0
4 Item4 20 0
5 Item5 15 0
6 item6

答案 1 :(得分:2)

您的代码确实很难掌握,所以我重新编写了一下,以便您可以了解它的要旨:

items = []

def add_items():
  number = int(input("Number: "))
  name = input("Name: ")
  items.append([name, number])

if __name__ == "__main__":
  while input("New?") == "y":
    add_items()
  print(items)

答案 2 :(得分:1)

您的代码中有太多错误。 pritall函数正在打印太多项目,这些项目不在myitems列表中。这样做是为了让您遍历列表并打印遇到的每个元素。另一件事,当您要将某些内容添加到列表列表时,要添加的数据类型必须是列表。因此,您应该收集用户输入并从中列出一个列表。然后将该列表追加到列表列表中。

您想要的是什么

myitems = [[1,"Item1",100,0],[2,"Item2",150,0],[3,"Item3",75,0],[4,"Item4",20,0],[5,"Item5",15,0]]

def printall():
    for x in myitems: 
        print(x)

def new():
    userinput = input("New?:")
    if userinput == "y":
        userinput_number = int(input("Please enter a number:"))
        userinput_name = input("Please enter a name:")
        entry = [len(myitems), userinput_number, userinput_name, 0]
        myitems.append(entry)

答案 3 :(得分:1)

我认为这是最简单的方法:

myitems = [[1, "Item1", 100, 0], [2, "Item2", 150, 0], [3, "Item3", 75, 0], [4, "Item4", 20, 0], [5, "Item5", 15, 0]]

def printall():
    for x in myitems:
        print(x[0], x[1], x[2], x[3])

def new():
    userinput = input("New?:")
    if userinput == "y":
        new = []
        userinput = int(input("Please enter first number:"))
        new.append(userinput)
        userinput = input("Please enter a name:")
        new.append(userinput)
        userinput = int(input("Please enter second number:"))
        new.append(userinput)
        userinput = int(input("Please enter second number:"))
        new.append(userinput)
        myitems.append(new)

new()
printall()