我可以使用pop()函数传递用户输入吗?

时间:2019-06-09 22:02:15

标签: python python-3.x

我有一个作业问题,我想对此做些改进。这个想法是允许用户在给定一些选项的情况下“将物品放入背包”。我有那部分。我想做的是一旦用户输入“选择”了项目,就使用pop()函数从列表中删除项目。如何获取pop()以字符串形式1-4传递随机用户输入?

我尝试将pop()内的值设置为“ input()”和“ itemToAdd”变量。

import sys

itemsForBackpack = ["1", "2", "3", "4"]
itemsForBackpack = ["book", "computer", "keys", "travel mug"]


while True:
    print("Would you like to:")
    print("1. Add an item to the backpack?")
    print("2. Check if an item is in the backpack?")
    print("3. Quit")
    userChoice = input()

    if(userChoice == "1"):
        print("What item do you want to add to the backpack?" + " Select the number representing the item you wish from left to right eg '1 = book'."+ str(itemsForBackpack))
        itemToAdd = input()
        if itemToAdd == "1":
            print(str(itemsForBackpack[0]))
        elif itemToAdd == "2":
            print(str(itemsForBackpack[1]))
        elif itemToAdd == "3":
            print(str(itemsForBackpack[2]))
        elif itemToAdd == "4":
            print(str(itemsForBackpack[3]))
        return_value = itemsForBackpack.pop()
        print('return_value: ', return_value)
        print("Updated List: ", itemsForBackpack)
        break

    if(userChoice == "2"):
        print("What item do you want to check to see if it is in the backpack?")
        itemToCheck = input()

我认为它想要一个整数,因为我收到一条错误消息,说字符串不能显示为整数。

1 个答案:

答案 0 :(得分:1)

如果我正确理解了您的问题,则可以这样做:

itemsForBackpack = ["book", "computer", "keys", "travel mug"]

itemToAdd = "2"

print('before:', itemsForBackpack)
print('removing: ', itemsForBackpack.pop(int(itemToAdd)-1))
print('after:', itemsForBackpack)

输出:

before: ['book', 'computer', 'keys', 'travel mug']
removing:  computer
after: ['book', 'keys', 'travel mug']

要删除随机项,您可以使用random.choice()进行选择,并使用列表的remove()方法摆脱它(而不是pop()):

import random

itemsForBackpack = ["book", "computer", "keys", "travel mug"]

randomItemToRemove = random.choice(itemsForBackpack)

print('before:', itemsForBackpack)
print('removing: ', randomItemToRemove)
itemsForBackpack.remove(randomItemToRemove)
print('after:', itemsForBackpack)