Python 将项目从一个列表带到另一个列表的更干净的方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18440231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cleaner Way to Take Items from One List to Another
提问by user2717129
I've been writing a text adventure game, and at one point I need to take an item, which is given by user input, from one list and move it to another list. Specifically, is there any way to get the index of an item when you know the item name besides something like:
我一直在写一个文本冒险游戏,有一次我需要从一个列表中取出一个由用户输入给出的项目,然后将它移动到另一个列表中。具体来说,当您知道项目名称时,除了以下内容之外,还有什么方法可以获得项目的索引:
list_one = ["item one", "item two"]
index_one = list_one.index("item one")
The code I'm using in my script is:
我在脚本中使用的代码是:
player.items.append(start_room.items.pop(start_room.items.index(next)))
Where next is the input, and this seems very messy. If there's an easier way to go about this, let me know. Thanks!
接下来是输入,这看起来很混乱。如果有更简单的方法来解决这个问题,请告诉我。谢谢!
采纳答案by Hyperboreus
If you already know the item, there is no need to call index
or pop
or whatever:
如果你已经知道的项目,则不需要调用index
或pop
或什么:
list_one.remove (item)
list_two.append (item)
回答by Alex
I prefer to use return of pop()
method :
我更喜欢使用pop()
方法的返回:
list_two.append( list_one.pop( list_one.index( item ) ) )
And if suddenly you decide to need index, you don't need to change much :
如果您突然决定需要索引,则不需要进行太多更改:
i = list_one.index( item )
list_two.append( list_one.pop( i ) )