我希望第一个if ... else
语句同时检查a
和b
。我想要一种有效的计数no_of_good和no_of_poor的方法,以最大程度地减少代码行数。可能吗?
如何在if语句中同时打印a
和b
?还有如何计算好坏计数?
a = 1
b = 3
good_count=0
poor_count=0
if a in range(0,6) and b in range(0,6):
//print and count
elif a in range(6,10) and b in range(6,10):
//pprint and count
这是完成工作的一种很长的方法:
a = 1
b = 3
good_count=0
poor_count=0
if a in range(0,6):
print("a = GOOD")
good_count+=1`
elif a in range(6,10):
print("a = POOR")
poor_count+=1
if b in range(0,6):
print("b = GOOD")
good_count+=1
elif b in range(6,10):
print("b = POOR ")
poor_count+=1
print("no_of_good=",good_count," ","no_of_poor=",poor_count)
实际输出:
a = GOOD
b = GOOD
no_of_good= 2 no_of_poor= 0
预期的输出也应该相同,但是使用任何不同的方法
答案 0 :(得分:1)
If you don't want to repeat your if statements then you could look into having a datatstructure to hold your values and iterate over all the values.
I also changed the condition to use integer comparisson instead of a range; it seames cleaner in my opinion.
Here is an example using a dict
to hold the data:
data = {
'a': 1,
'b': 3,
'c': 5,
'd': 6,
}
good_count = 0
poor_count = 0
for k, v in data.items():
if 0 <= v <= 5:
good_count += 1
result = 'GOOD'
else:
poor_count += 1
result = 'POOR'
print('{} = {}'.format(k, result))
print('no_of_good = {}'.format(good_count))
print('no_of_poor = {}'.format(poor_count))
And this is the output:
a = GOOD
b = GOOD
c = GOOD
d = POOR
no_of_good = 3
no_of_poor = 1
Does that help you?
答案 1 :(得分:0)
如果您不关心变量a,b,c,d
等,则可以使用列表,并使用lis t的索引来打印GOOD
或POOR
>
li = [1,3,5,6]
good_count = 0
poor_count = 0
#Iterate through the list
for idx, item in enumerate(li):
#Check the condition on the item and print accordingly
if 0 <= item <= 5:
good_count+=1
print('index {} = GOOD'.format(idx))
elif 6<= item <= 10:
poor_count+=1
print('index {} = POOR'.format(idx))
#Print final good and poor count
print('no_of_good = {}'.format(good_count))
print('no_of_poor = {}'.format(poor_count))
输出如下:
index 0 = GOOD
index 1 = GOOD
index 2 = GOOD
index 3 = POOR
no_of_good = 3
no_of_poor = 1