问题描述
因此,我希望将这些数字分为几组,如下所示,和是不正确的,并希望知道这样做的正确方法。
在“ if”代码之后,它将分配一个与分数一致的等级,然后将1加到计数器中,该计数器对具有该等级的组数进行计数。
#determining the meal rating and counting number of applied ratings and priniting
def mealrating(score):
for x in range(0,len(score)):
if 1 < and score[x] >3:
review[x] = poor
p = p + 1
if 4 < and score[x] >6:
review[x] = good
g = g + 1
if 7 < and score[x] >10:
review[x] = excellent
e = e + 1
print('\n')
print('%10s' % ('Poor:', p ))
print('%10s' % ('Good', g ))
print('%10s' % ('Excellent', e ))
1楼
线
if 1 < and score[x] >3:
就是行不通。
and
连接两个表达式,所以它看起来像
if (1 <) and (score[x] > 3):
1 <
只是没有意义。
一个快速的解决方法是
if 1 < score[x] and score[x] > 3:
但这似乎并不意味着您-毕竟,它检查score [x]是否大于1且大于3,这是多余的。 你可能是说
if 1 < score[x] and score[x] < 3:
哪个检查score [x]在1和3之间(不包括在内)。 然后有一个最后的技巧,Python允许您通过一次检查将其编写为:
if 1 < score[x] < 3:
尽管如果要像这样比较多个范围,则可能需要将<
s更改为<=
,因为否则,如果score[x]
恰好是边界之一,则所有范围都会失败。
2楼
您可以使用来帮您解决这个问题。 文档中的示例可以根据您的情况轻松修改:
from bisect import bisect
from collections import Counter
def grade(score, breakpoints=[3,6], grades='PGE'):
i = bisect(breakpoints, score)
return grades[i]
for k,v in Counter(grade(i) for i in [1,2,3,4,514,35,65,80]).iteritems():
print('Grade: {} # of Awards: {}'.format(k,v))
使用示例运行时的外观如下:
>>> for k,v in Counter(grade(i) for i in [1,2,3,456,342,90]).iteritems():
... print('Grade: {} # of Awards: {}'.format(k,v))
...
Grade: P # of Awards: 2
Grade: E # of Awards: 3
Grade: G # of Awards: 1
3楼
可能是您想要这样的东西:
if 1 < score[x] and score[x] <3:
review[x] = poor
p = p + 1
在对结果求和后,“ and”的两面都应有表达式,以求值。 因此它分别评估(1 <score [x])和(score [x] <3),并且将两个结果“和”。