python3在带有用户inpu的列表中的位置更改

2024-09-27 17:38:34 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我有点迷路了。我知道如何在代码中插入一个值[Example-x.insert(2,99)],但我最担心的是,如果我试图让用户告诉我他们希望项目在列表中的位置在哪里。在

示例

库存=[匕首,剑,盾牌,胸甲,头盔]

这就是我所拥有的,我知道它行不通。在

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

我只想让它显示一个更新的位置列表,如果用户想把拼写本移到前面,这样就可以把所有其他项目都往后推。我在这干了一整天,我已经筋疲力尽了。帮忙吗?在


Tags: 项目代码用户示例列表exampledef库存
2条回答

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

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= int(input("Number: "))
inventory.insert(0,inventory.pop(item))

*这适用于python 2和python 3

相关问题 更多 >

    热门问题