【问题标题】:Generator failing with NoneType error生成器因 NoneType 错误而失败
【发布时间】:2014-08-22 17:52:59
【问题描述】:

我正在制作文字RPG,其中一个游戏命令是statistics。它会打印所有玩家的统计数据,其中之一是Defense Strength,它由玩家库存的第二个和第三个 (1, 2) 插槽中的防御项目决定。游戏中的所有物品都是item 类的实例,并具有Str(强度)属性。玩家的物品栏是一个包含 5 个插槽(永远不会更改)的列表,空插槽用 None 表示。

要打印玩家的防御强度,对于 Inventory 列表中的每个项目,如果它不是 None,或者在布尔语句中为 True,我想添加它的 Str 值(总是一个 int)来创建一个总数总和。

这就是我所拥有的:

print('- Defense Strength:', sum(i.Str for i in Inventory[1:3] if Inventory[i]))

但是这会失败并出现错误TypeError: list indices must be integers, not NoneType 我该如何解决这个问题!?

PS:尽管我只迭代了 2 个索引,但我只想在 1 行中创建此语句,因为它非常简单。

【问题讨论】:

    标签: python list generator


    【解决方案1】:

    使用if i,而不是if Inventory[i],您正在尝试使用NoneType 进行索引

    您已经在迭代 Inventory 项目,因此 if i 将过滤 NoneTypes

    你基本上是在做:

    l = [1,2,None,None]
    for i in l:
        if l[i]: # trying to access list using None as an index
            print (i)
    
    TypeError: list indices must be integers, not NoneType
    

    什么时候该做:

    for i in l:
        if i: # check if element is not None
           print (i)
    1 # prints values that are not None
    2
    

    【讨论】:

      猜你喜欢
      • 2022-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多