Python 根据列表中的值输入if语句
我用一个包含所有分数的列表Python 根据列表中的值输入if语句,python,list,if-statement,Python,List,If Statement,我用一个包含所有分数的列表playerScores制作了一个计分系统 # Fake sample data playerScores = [5, 2, 6, 9, 0] 我希望当列表中的任何分数等于或小于0时运行if语句 我试过了 if playerScores <= 0: if playerScores您的playerScores变量是一个列表。尝试将其与0(或任何数字)进行比较不会太好 >>> a = [1, 2] >>> a <=
playerScores
制作了一个计分系统
# Fake sample data
playerScores = [5, 2, 6, 9, 0]
我希望当列表中的任何分数等于或小于0时运行if语句
我试过了
if playerScores <= 0:
if playerScores您的playerScores
变量是一个列表。尝试将其与0
(或任何数字)进行比较不会太好
>>> a = [1, 2]
>>> a <= 0
False
如果您只想检查是否存在任何,则可以将any
与生成器表达式结合使用,以检查是否有任何列表元素小于或等于0
playerScores = [5, 2, 6, 9, 0]
if any(score <= 0 for score in playerScores):
# At least one score is <= 0
playerScores=[5,2,6,9,0]
如果有(得分)
flag = False
for item in playerScores:
if item <= 0:
flag = True
break
if flag:
## Do something
>>> a(1)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
a(1)
TypeError: 'list' object is not callable
>>> a[1]
2
playerScores = [5, 2, 6, 9, 0]
if any(score <= 0 for score in playerScores):
# At least one score is <= 0