python - 统计列表中符合特定条件的元素

标签 python

我有一个列表,说:

   list = ['KAYE', 'DAVID', 'MUSIC', '88', 'ART', '45', 'FRENCH', '36']

我想统计列表中有多少个小于50的标记,所以我写了:

count = 0
if  list[3] < '50' or list[5] < '50' or list[7] < '50':
    count = count + 1

但计数始终为1,当有多个小于50的标记时不累加。

我该如何解决这个问题?非常感谢您的帮助

最佳答案

您正在运行一个测试,该测试会查看多种可能的条件,并在其中任何条件为真时执行一段代码。

我想你想统计有多少分数是 <50,然后报告总数。

让我们做一个简单的版本,然后从那里发展:

student = ['KAYE', 'DAVID', 'MUSIC', '88', 'ART', '45', 'FRENCH', '36']
ALARM = 50

num_alarms = 0

if int(student[3]) < ALARM:
    num_alarms += 1
    print("Alarm! The " + student[2] + " grade is too low!")

if int(student[5]) < ALARM:
    num_alarms += 1
    print("Alarm! The " + student[4] + " grade is too low!")

if int(student[7]) < ALARM:
    num_alarms += 1
    print("Alarm! The " + student[6] + " grade is too low!")

if num_alarms != 0:
    print("There were " + str(num_alarms) + " grades too low.")

这就是我认为您正在尝试做的事情。但我们可以稍微清理一下:

student = ['KAYE', 'DAVID', 'MUSIC', '88', 'ART', '45', 'FRENCH', '36']
ALARM = 50

num_alarms = 0

# count from 3 .. by 2
for score in range(3,len(student), 2):
    if int(student[score]) < ALARM:
        print("Alarm! The " + student[score-1] + " grade is too low!")
        num_alarms += 1

if num_alarms != 0:
    print("There were " + str(num_alarms) + " grades too low.")

最后,我们可以使用“完整的 Python”并添加列表理解:

alarms = [ student[class_] for class_ in range(2, len(student), 2) if int(student[class_ + 1]) < ALARM ]

for class_ in alarms:
    print("Alarm! The " + class_ + " grade is too low!")

num_alarms = len(alarms)

if num_alarms != 0:
    print("There were " + str(num_alarms) + " grades too low.")

关于python - 统计列表中符合特定条件的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34983059/

相关文章:

python - 调用 Request.finish 后在请求上调用 Twisted 错误 : Request. write

python - 用 Numpy 数组简洁地堆叠一个常量?

python - 如何使用openpyxl设置图表标签的间隔单位

python - 向量化 numpy 折扣计算

python - 多次导入一个模块有多安全?

python - 如何在django中的模型字段之间执行算术运算

python - 没有名为 'nltk' 的模块

python - 错误:how to fix the swift error type to my server

python - 使用 pyodbc 将数字插入表中

python - 如何更好的基于配置文件实例化不同的子类?