标签:
方法1: 1!/usr/bin/env python 2 # coding=utf-8 3 4 #产生一个列表,其中有40个元素,每个元素是0到100的一个随机整数 5 #如果这个列表中的数据代表着某个班级40人的分数,请计算成绩低于平均分的学生人数,并输出 6 #对上面的列表元素从大到小排序 7 import random 8 #导入random模块 9 lst_number = random.sample(range(0,100),40) 10 #利用range生成0到100的整数,然后调用random模块的sample方法在0到100中随机生成40个数字 11 print ‘随机数:‘,lst_number 12 sun = 0 13 mean = 0 14 for i in lst_number: 15 sun=sun+i 16 mean = sun /40 17 print ‘总和:‘,sun 18 print ‘平均值:‘,mean 19 20 score = [] 21 for i in lst_number: 22 if i < mean: 23 score.append(i) 24 score.sort() 25 print ‘低于平均分的为:‘, score [root@Sammy pythonspace]# python lianxi2.py 随机数: [25, 35, 63, 56, 89, 16, 98, 51, 78, 59, 19, 4, 40, 50, 38, 79, 96, 23, 94, 29, 99, 93, 70, 13, 46, 54, 6, 39, 81, 90, 67, 62, 9, 57, 75, 27, 58, 86, 30, 92]总和: 2196平均值: 54低于平均分的为: [4, 6, 9, 13, 16, 19, 23, 25, 27, 29, 30, 35, 38, 39, 40, 46, 50, 51]方法2:#!/usr/bin/env python # coding=utf-8 from __future__ import division import random score = [random.randint(0,100) for i in range(40)] #0到100之间,随机得到40个整数,组成列表 print score num = len(score) sum_score = sum(score) #对列表中的整数求和 ave_num = sum_score/num #计算平均数 less_ave = len([i for i in score if i<ave_num]) #将小于平均数的找出来,组成新的列表,并度量该列表的长度 print "the average score is:%.1f" % ave_num print "There are %d students less than average." % less_ave sorted_score = sorted(score, reverse=True) #对原列表排序 print sorted_score[root@Sammy pythonspace]# python lianxi2.py [63, 76, 58, 33, 46, 72, 17, 52, 89, 58, 67, 79, 95, 52, 90, 43, 37, 20, 62, 72, 20, 50, 48, 59, 83, 27, 83, 55, 36, 95, 3, 6, 95, 83, 38, 11, 4, 94, 39, 34]the average score is:53.0There are 20 students less than average.[95, 95, 95, 94, 90, 89, 83, 83, 83, 79, 76, 72, 72, 67, 63, 62, 59, 58, 58, 55, 52, 52, 50, 48, 46, 43, 39, 38, 37, 36, 34, 33, 27, 20, 20, 17, 11, 6, 4, 3]产生一个列表,其中有40个元素,每个元素是0到100的一个随机整数
标签:
原文地址:http://www.cnblogs.com/gyming/p/ca0b398ee00056130538626beba6d794.html