python – 在列表中添加/删除项目
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 在列表中添加/删除项目,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1716字,纯文字阅读大概需要3分钟。
内容图文
![python – 在列表中添加/删除项目](/upload/InfoBanner/zyjiaocheng/790/d9381f87c08b4443b0a923a50619611d.jpg)
我正在尝试创建一个可以添加和删除其库存中的商品的玩家.我有一切工作,我只有一个小问题.每次打印清单时,也会显示“无”.我一直在搞乱它试图删除它,但不管我做什么,“无”总是出现在程序中!我知道我只是错过了一些简单的事情,但我无法理解我的生活.
class Player(object):
def __init__(self, name, max_items, items):
self.name=name
self.max_items=max_items
self.items=items
def inventory(self):
for item in self.items:
print item
def take(self, new_item):
if len(self.items)<self.max_items:
self.items.append(new_item)
else:
print "You can't carry any more items!"
def drop(self, old_item):
if old_item in self.items:
self.items.remove(old_item)
else:
print "You don't have that item."
def main():
player=Player("Jimmy", 5, ['sword', 'shield', 'ax'])
print "Max items:", player.max_items
print "Inventory:", player.inventory()
choice=None
while choice!="0":
print """
Inventory Man
0 - Quit
1 - Add an item to inventory
2 - Remove an item from inventory
"""
choice=raw_input("Choice: ")
print
if choice=="0":
print "Good-bye."
elif choice=="1":
new_item=raw_input("What item would you like to add to your inventory?")
player.take(new_item)
print "Inventory:", player.inventory()
elif choice=="2":
old_item=raw_input("What item would you like to remove from your inventory?")
player.drop(old_item)
print "Inventory:", player.inventory()
else:
print "\nSorry, but", choice, "isn't a valid choice."
main()
raw_input("Press enter to exit.")
解决方法:
问题是这句话:
print "Inventory:", player.inventory()
你告诉Python打印从player.inventory()返回的值.但是您的inventory()方法只打印库存,它不返回任何内容 – 因此返回值隐式为None.
您可能希望明确选择以下内容:
print "Inventory:"
player.print_inventory()
或者你可以让它返回一个字符串并执行此操作:
print "Inventory:", player.inventory_as_str()
内容总结
以上是互联网集市为您收集整理的python – 在列表中添加/删除项目全部内容,希望文章能够帮你解决python – 在列表中添加/删除项目所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。