python - 生成器因 NoneType 错误而失败

标签 python list generator

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

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

这就是我所拥有的:

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

但是,此操作失败并出现错误TypeError:列表索引必须是整数,而不是 NoneType 我该如何解决这个问题!?

PS:尽管我只迭代 2 个索引,但我想仅用 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

关于python - 生成器因 NoneType 错误而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25452915/

相关文章:

java - 遍历节点列表,this = this.next在java中不起作用?

c# - 将不同的列表转换为字典不起作用

python - 如何在保存之前修改Django表单?

Android:SectionIndexer 的自定义 View 布局和动态禁用 SectionIndexer

python - Windows 上的 PyGObject

javascript - 如何克隆 ES6 生成器?

c# - .NET 中有 XML 表单生成器吗?

PHP API key 生成器

python - 使用 JS + Python 延迟查找 facebook cookie

python - 在 Django 中运行迁移时出现 mysqlclient 错误