For Loop追加到另一个列表
我正在为我正在设计的游戏“拾取所有”和“全部丢弃”。玩家拥有一个库存(库存),每个房间都有自己的存储空间来跟踪其内容。当它是一个特定的项目时,我可以轻松地追加或从相应的列表中删除该项目,但是当它适用于所有项目时,我不知道如何继续。 (注:我不知道有多少项目是在库存为随着玩家需要和掉落物品会改变)For Loop追加到另一个列表
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失误这里
- 你转换为大写,但对降低测试!
- 你应该反覆的
ROOMNAMEinventory
复制,修改列表,而不是推荐迭代它:它改变列表到['string', 'lamp'] and ['coin']
:不是说你想
固定码:
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'] []
回答:
在Python List
支持添加ö NE另一:
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))
以上是 For Loop追加到另一个列表 的全部内容, 来源链接: utcz.com/qa/264187.html