根据lis中的值输入if语句

2024-09-28 04:22:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我用一个包含所有分数的列表playerScores建立了一个评分系统

# Fake sample data    
playerScores = [5, 2, 6, 9, 0]

当列表中的任何分数等于或小于0时,我希望运行if语句

我试过了

if playerScores <= 0:

但我被告知名单是不可收回的


Tags: sample列表dataif系统语句评分分数
2条回答

您的playerScores变量是一个列表。尝试将其与0(或任何数字)进行比较不会太好。你知道吗

>>> a = [1, 2]
>>> a <= 0
False

而是使用for循环来检查列表中的每个项

for item in playerScores:
    if item <= 0:
        ## Do something

如果您只想检查是否有<= 0,那么只需将条件设置为False,然后将其更改为True,如果您找到了一个。你知道吗

flag = False
for item in playerScores:
    if item <= 0:
        flag = True
        break

if flag:
    ## Do something

我不知道为什么会出现list not callable错误。使用与列表的比较(如上所示)只会返回False。要得到你提到的错误,你需要这样的东西

>>> a(1)

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    a(1)
TypeError: 'list' object is not callable

在这里,您试图将列表作为函数function()调用,而不是索引它list[]

>>> a[1]
2

可以将any与生成器表达式结合使用,以检查是否有任何列表元素小于或等于0。你知道吗

playerScores = [5, 2, 6, 9, 0]
if any(score <= 0 for score in playerScores):
    # At least one score is <= 0

相关问题 更多 >

    热门问题