gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:03:56 24 4
gpt4 key购买 nike

我正在制作一个文本角色扮演游戏,游戏命令之一是统计。它打印玩家的所有统计数据,其中之一是防御强度,它由玩家库存的第二个和第三个 (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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com