For Loop Append to list from another

时间:2016-09-13 14:49:57

标签: python list

我正在为我正在设计的游戏“全力以赴”和“全力以赴”。玩家有一个库存(库存),每个房间都有自己的库存,以跟踪其中的内容。当它是一个特定的项目时,我可以轻松地从相应的列表中追加或删除该项目,但是当它适用于所有项目时,我不知道如何继续。 (注意:我不知道库存中有多少项目,因为当玩家拿走和丢弃物品时它会发生变化)

ROOMNAMEinventory = ['lamp', 'coin']
inventory = ['string']
do = raw_input("What would you like to do?").upper()
if(do == 'drop all'):
  for items in ROOMNAMEinventory:
    inventory.append(items)
    ROOMNAMEinventory.remove(items)
print inventory
print ROOMNAMEinventory

目前,这打印出来:

['string', 'lamp']
['coin']
None

为什么要打印无?

2 个答案:

答案 0 :(得分:1)

Python中的

List支持将一个添加到另一个:

roomname_inventory = ['lamp', 'coin']
inventory = ['string']
do = raw_input("What would you like to do?").upper()
if (do == 'DROP ALL'):
    inventory += roomname_inventory
    roomname_inventory = []
print inventory
print roomname_inventory

但是如果你只是想在迭代时删除修改列表,你也可以这样做:

if (do == 'DROP ALL'):
    while roomname_inventory:
        inventory.append(roomname_inventory.pop(0))

答案 1 :(得分:0)

这里有2个错误

  1. 你转换为大写但是对着较低的版本进行测试!
  2. 你应该迭代ROOMNAMEinventory的副本,修改列表,而不建议迭代它:它将列表更改为['string', 'lamp'] and ['coin']:不是你想要的
  3. 固定代码:

    ROOMNAMEinventory = ['lamp', 'coin']
    inventory = ['string']
    do = raw_input("What would you like to do?").upper()
    if(do == 'DROP ALL'):  # upper vs upper: could work :)
      for items in ROOMNAMEinventory[::]:  # iterate on a copy of the list
        inventory.append(items)
        ROOMNAMEinventory.remove(items)
    print inventory
    print ROOMNAMEinventory
    

    结果(输入drop all时)

    ['string', 'lamp', 'coin']
    []