简体   繁体   English

带有用户输入的列表中的python 3位置更改

[英]python 3 position change in a list with user input

Okay, so I'm kind of lost here. 好吧,所以我有点迷路了。 I understand how to insert a value into the code myself [Example - x.insert(2, 99)] but what I'm getting hung up on is what happens if I'm trying to get the user to tell me where they want the item to be in regards to position in the list. 我知道自己如何在代码中插入一个值[示例-x.insert(2,99)],但是我挂在嘴上的是如果我试图让用户告诉我他们想要的位置会发生什么与列表中的位置有关的项目。

Example

inventory = [dagger, sword, shield, breastplate, helmet] 库存= [匕首,剑,盾,胸甲,头盔]

this is what I have and I know it doesn't work. 这就是我所拥有的,我知道这行不通。

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

I just want it to show an updated position list if the user wanted to move say, the spellbook to the front, thus pushing back all other items. 我只希望它显示一个更新的位置列表,前提是用户想将咒语簿移到最前面,从而将所有其他项目都推回去。 I've been at this all day and I'm spent. 我整天都在这里,我花了很多时间。 Help? 救命?

After reading the item and new index for the item as a number, find it in the list, pop it, and insert it into the list at that index. 在读取项目和该项目的新索引后,将其作为数字读取,在列表中找到它,将其弹出,然后将其插入到该索引处的列表中。

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)

How about something like this: 这样的事情怎么样:

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

*This works on python 2, and python 3 *这适用于python 2和python 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM