【问题标题】:python 3 position change in a list with user inputpython 3在用户输入列表中的位置变化
【发布时间】:2017-03-02 20:50:11
【问题描述】:

好的,所以我有点迷路了。我知道如何自己在代码中插入一个值 [Example - x.insert(2, 99)],但我正在挂断的是如果我试图让用户告诉我他们想要的地方会发生什么与列表中的位置有关的项目。

例子

inventory = [匕首、剑、盾、胸甲、头盔]

这是我所拥有的,我知道它不起作用。

def edit_it():
    inventory = ["orb", "staff", "spellbook", "hat", "potion", "robe"]
    inventory[item] = input("Number: ")
    print(inventory)

如果用户想将法术书移到前面,我只是希望它显示一个更新的位置列表,从而将所有其他项目推后。我整天都在做这件事,我已经筋疲力尽了。帮忙?

【问题讨论】:

    标签: python list python-3.x arraylist


    【解决方案1】:

    在读取项目和项目的新索引作为数字后,在列表中找到它,将其弹出,然后将其插入到该索引处的列表中。

    def edit_it():
        inventory = ["orb", "staff", "spellbook", "hat", "potion", "robe"]
        item = input("Which item do you want to move? ")
        new_index = int(input("Number: "))
        inventory.insert(new_index, inventory.pop(inventory.index(item)))
        print(inventory)
    

    【讨论】:

    • 试过了,但我现在收到项目的名称错误。
    • 您需要从输入中读取项目:item = input("What item do you want to move? ") 我会更新答案。
    【解决方案2】:

    这样的事情怎么样:

    item= int(input("Number: "))
    inventory.insert(0,inventory.pop(item))
    

    *这适用于 python 2 和 python 3

    【讨论】:

    • 也适用于 python3
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 2016-02-05
    • 2015-10-17
    • 1970-01-01
    相关资源
    最近更新 更多