現在有如下的需求:
''' 實現這樣的一個功能: 對一個班級的學生的成績做出一些評定,評定規則是: one: [0-60) -- F two: [60-70) -- D three: [70-80) -- C four: [80-90) -- B five: [90-100] -- A'''
python中的bisect可以實現上面的需求
運行效果:
#python bisect''' 實現這樣的一個功能: 對一個班級的學生的成績做出一些評定,評定規則是: one: [0-60) -- F two: [60-70) -- D three: [70-80) -- C four: [80-90) -- B five: [90-100] -- A ######################################### 你很可能先想到使用:if....else... 或者想到使用:switch...(java) ########################################## 下面給出不使用以上兩種方式實現這一功能'''import randomimport bisectdef create_student_scores(n): #根據學生人數n,建立學產生績 if n >= 0: scores = [] for x in range(n): scores.append(random.randrange(0, 101, 1)) return scores else: print('the number should be greater than 0!') def grade(score, breakpoints = [60, 70, 80, 90], grades = 'FDCBA'): i = bisect.bisect(breakpoints, score) return grades[i]def main(): student_scores = create_student_scores(10) student_results = [grade(score) for score in student_scores] print('學產生績:{}\n評定結果:{}'.format(student_scores, student_results))if __name__ == '__main__': main()