首页 文章

Python:如何将用户输入添加到列表中?

提问于
浏览
1
  • 我不确定如何通过基于项类型的映射来获取用户输入并将其添加到列表中 .

  • 在下面的代码示例中,选择一个选项后,将提示用户输入项目类型,即单个字母(b,m,d,t,c) .

  • 一旦用户输入该字母然后输入成本,我需要存储在列表中 .

  • 例如,如果输入b然后10.在列表中它应该显示为[(Bike,10)]而不是[(b,10)] . 因此,稍后打印出列表时,它将打印为[(Bike,10)]而不是[(b,10)],这增加了可读性 .

我甚至不确定如何弄明白或尝试 . 另外,对于 Headers 中的不良措辞感到抱歉 . 我对此很陌生,不知道如何说出问题 .

代码

while True:
    print "1. Add an item."
    print "2. Find an item."
    print "3. Print the message board."
    print "4. Quit."
    choice = input("Enter your selection: ")
    if choice == 1:
        item = raw_input("Enter the item type-b,m,d,t,c:")
        cost = raw_input("Enter the item cost:")
        elts = []
        elts.append([item,cost])
        if choice == 4:
            print elts
            break

1 回答

  • 2

    使用词典 . 这是关于如何在这种情况下使用它们的示例:

    elts = []
    
    items = {
        'b': 'Bike',
        'm': 'Motorcycle',
        'd': 'Dodge',
        't': 'Trailer',
        'c': 'Car',
    }
    
    while True:
        print "1. Add an item."
        print "2. Find an item."
        print "3. Print the message board."
        print "4. Quit."
        choice = input("Enter your selection: ")
        if choice == 1:
            item = raw_input("Enter the item type-b,m,d,t,c:")
            cost = raw_input("Enter the item cost:")
            elts.append([items[item],cost])
        if choice == 4:
            print elts
            break
    

    输出如下:

    1. Add an item.
    2. Find an item.
    3. Print the message board.
    4. Quit.
    Enter your selection: 1
    Enter the item type-b,m,d,t,c:b
    Enter the item cost:30
    1. Add an item.
    2. Find an item.
    3. Print the message board.
    4. Quit.
    Enter your selection: 1
    Enter the item type-b,m,d,t,c:c
    Enter the item cost:40
    1. Add an item.
    2. Find an item.
    3. Print the message board.
    4. Quit.
    Enter your selection: 4
    [['Bike', '30'], ['Car', '40']]
    

相关问题