更清洁的方法从一个列表中删除项目并添加到另一个列表(新手)

时间:2014-02-28 09:25:57

标签: python python-2.7

我有一个家庭作业,我需要创建一个简单的游戏,男人进入“建筑物”,并打开几扇门继续前进。为了做到这一点,他必须从地面拿走物品并将它们添加到他的库存中。

请参阅我的代码示例:

inventory = []
ground = ['item1', 'item2', 'item3']

def take_item(item):
    if item in ground:
        inventory.append(item)
        ground.remove(item)
        print "Item taken"
    else:
        print "There is nothing here"

take_item('item1')
print inventory
print ground
take_item('item1')

结果还可以:

Item taken 
inventory = ['item1'] 
ground = ['item2', 'item3']
There is nothing here

我的问题是,是否有更清晰和/或更多的蟒蛇方式从一个列表中删除项目并将其添加到另一个列表?

谢谢。

3 个答案:

答案 0 :(得分:2)

你的代码通常都很好,没有明显的问题,虽然取决于你问的是谁,尝试一些东西可能更pythonic然后抛出异常,如果它不起作用而return而不仅仅是打印,如:

def take_item(item):
    try:
        ground.remove(item)
        inventory.append(item)
        return "Item Taken"
    except ValueError:
        return "There is nothing here"

虽然一般全局变量有点禁止,但我建议将它们作为输入并使其更加模块化:

def take(item, ground, inventory):

然后一次返回所有内容,这将使整个函数看起来像这样:

    def take_item(item, ground, inventory):
    try:
        ground.remove(item)
        inventory.append(item)
        message = "Item Taken"
    except ValueError:
        message = "There is nothing here"
    return message, ground, inventory

但是你的第一次尝试非常棒,在你需要之前不需要优化代码。

答案 1 :(得分:1)

嗯,afaict,你的解决方案对我来说看起来非常精细和pythonic。

def take_item(item):
    if item in ground:
        inventory.append(item)
        ground.remove(item)

是一个很好的算法,因为它非常清楚它的作用,所以当你或其他人阅读它时,他就能理解代码在做什么。

答案 2 :(得分:0)

link显示list中移除的时间复杂度为O(n),在这种情况下最好尝试set