【问题标题】:Coding in Python, print command does not act as expected在 Python 中编码,打印命令未按预期运行
【发布时间】:2014-10-19 01:08:48
【问题描述】:
inventory = {
    'gold' : 500, 
    'sack' : ['rock', 'copper wire'],
    'weapons rack' : ['pistol', 'MP-5', 'grenade'],
    'ammo pouch' : ['Pistol ammo', 'MP-5 ammo'],
}

print "You have " + inventory['gold'][0] + " coins!"

我收到错误消息:

  line 8, in <module>
    print "You have " + inventory['gold'] + " coins!"
TypeError: 'int' object has no attribute '__getitem__'

为什么控制台不打印出"You have 500 gold coins!"

【问题讨论】:

    标签: python list dictionary printing


    【解决方案1】:

    您的gold 条目不是列表;您正在尝试索引 500 整数。删除[0]:

    print "You have", inventory['gold'], "coins!"
    

    请注意,我使用的是逗号,而不是 +,因为您不能像这样连接字符串和整数。另一种方法是先将整数转换为字符串:

    print "You have " + str(inventory['gold']) + " coins!"
    

    您也可以将黄金价值放入列表中:

    inventory = {
        'gold' : [500], 
        'sack' : ['rock', 'copper wire'],
        'weapons rack' : ['pistol', 'MP-5', 'grenade'],
        'ammo pouch' : ['Pistol ammo', 'MP-5 ammo'],
    }
    

    注意那里的500 值周围的[...] 方括号。然后你的[0] 再次申请:

    print "You have", inventory['gold'][0], "coins!"
    

    【讨论】:

      猜你喜欢
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多