2024-09-28 04:22:09 发布
网友
我用一个包含所有分数的列表playerScores建立了一个评分系统
playerScores
# Fake sample data playerScores = [5, 2, 6, 9, 0]
当列表中的任何分数等于或小于0时,我希望运行if语句
我试过了
if playerScores <= 0:
但我被告知名单是不可收回的
您的playerScores变量是一个列表。尝试将其与0(或任何数字)进行比较不会太好。你知道吗
0
>>> a = [1, 2] >>> a <= 0 False
而是使用for循环来检查列表中的每个项
for
for item in playerScores: if item <= 0: ## Do something
如果您只想检查是否有<= 0,那么只需将条件设置为False,然后将其更改为True,如果您找到了一个。你知道吗
<= 0
False
True
flag = False for item in playerScores: if item <= 0: flag = True break if flag: ## Do something
我不知道为什么会出现list not callable错误。使用与列表的比较(如上所示)只会返回False。要得到你提到的错误,你需要这样的东西
list not callable
>>> a(1) Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> a(1) TypeError: 'list' object is not callable
在这里,您试图将列表作为函数function()调用,而不是索引它list[]
function()
list[]
>>> a[1] 2
可以将any与生成器表达式结合使用,以检查是否有任何列表元素小于或等于0。你知道吗
any
playerScores = [5, 2, 6, 9, 0] if any(score <= 0 for score in playerScores): # At least one score is <= 0
您的
playerScores
变量是一个列表。尝试将其与0
(或任何数字)进行比较不会太好。你知道吗而是使用
for
循环来检查列表中的每个项如果您只想检查是否有
<= 0
,那么只需将条件设置为False
,然后将其更改为True
,如果您找到了一个。你知道吗我不知道为什么会出现
list not callable
错误。使用与列表的比较(如上所示)只会返回False
。要得到你提到的错误,你需要这样的东西在这里,您试图将列表作为函数
function()
调用,而不是索引它list[]
可以将
any
与生成器表达式结合使用,以检查是否有任何列表元素小于或等于0。你知道吗相关问题 更多 >
编程相关推荐