繁体   English   中英

如何计算python中大于和小于给定数字集的数字

[英]How to count the number greater than and less than a given set of numbers in python

Python 序列来统计分数大于和小于 50 的科目数。分数 50 及以下视为失败。

样本输入

科目数:

5

输入标记:

65

51

34

46

54

样品 OUTPUT

子通过:3

子失败:2

我的计划:

x=int(input("No. of subjects: \n"))
print("Enter marks:")
for i in range(x):
 y=[int(input())]
 count=0
 h=0
for j in y:
 if j>50:
  count=count+1
 if j<50:
  h=h+1
 print("Sub passed: " + str(count))
 print("Sub failed: " + str(h))
        

上面的程序在得到输入后没有返回任何值。

它可以更整洁一点:

x=int(input("No. of subjects: \n"))
print("Enter marks:")

y= [int(input()) for i in range(x)]
    
passed = len([y_p for y_p in y if y_p > 50])
not_passed = len([y_n for y_n in y if y_n< 50])

print(passed) #According to question would print: 3
print(not_passed) #According to question would print: 2

首先,您使用列表理解创建一个包含所有输入的列表。 然后,您制作另一个列表,其中条件已通过和未通过。

您需要在循环之外定义counth

x=int(input("No. of subjects: \n"))
print("Enter marks:")
count = 0
h = 0
for i in range(x):
    y=[int(input())]
    for j in y:
        if j>50:
            count=count+1
        if j<50:
            h=h+1
print("Sub passed: " + str(count))
print("Sub failed: " + str(h))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM