产⽣⼀个列表,其中有40个元素,每个元素是0到100的⼀个随
机整数
⽅法1:
python生成1到100之间随机数
1!/usr/bin/env python
2# coding=utf-8
3
4#产⽣⼀个列表,其中有40个元素,每个元素是0到100的⼀个随机整数
5#如果这个列表中的数据代表着某个班级40⼈的分数,请计算成绩低于平均分的学⽣⼈数,并输出
6#对上⾯的列表元素从⼤到⼩排序
7import random
8#导⼊random模块
9lst_number =random.sample(range(0,100),40)
10#利⽤range⽣成0到100的整数,然后调⽤random模块的sample⽅法在0到100中随机⽣成40个数字
11print'随机数:',lst_number
12sun =0
13mean =0
14for i in lst_number:
15sun=sun+i
16mean =sun /40
17print'总和:',sun
18print'平均值:',mean
19
20score =[]
21for i in lst_number:
22if i < mean:
23score.append(i)
24score.sort()
25print'低于平均分的为:', 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.0
There are 20students 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]

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。