python里对list中的整数求平均并排序,pythonlist
python里对list中的整数求平均并排序,pythonlist
问题
定义一个int型的一维数组,包含40个元素,用来存储每个学员的成绩,循环产生40个0~100之间的随机整数,
(1)将它们存储到一维数组中,然后统计成绩低于平均分的学员的人数,并输出出来。
(2)将这40个成绩按照从高到低的顺序输出出来。
解决(python)
#! /usr/bin python #coding:utf-8 from __future__ import division #实现精确的除法,例如4/3=1.333333 import random def make_score(num): score = [random.randint(0,100) for i in range(num)] return score def less_average(score): num = len(score) sum_score = sum(score) ave_num = sum_score/num less_ave = [i for i in score if i<ave_num] return len(less_ave) if __name__=="__main__": score = make_score(40) print "the number of less average is:",less_average(score) print "the every socre is[from big to small]:",sorted(score,reverse=True)
可以用
list.sort(key = int)
key的最用相当于构建值,列表中的每个值实际上会转变为key(value),上例则为 int(value)
也就是 ['1','2','11','22'].sort(key = int)相当于[int('1'),int('2'),int('11'),int('22')].sort()
key可以理解为用于list comprehension的函数 ['1','2','11','22'].sort(key = int) 相当于
[int(x) for x in ['1','2','11','22'] ].sort()
db.Account.find().sort([("UserName",pymongo.ASCENDING),("Email",pymongo.DESCENDING)])
相关内容
- python里大整数相乘相关技巧指南,python相乘
- 跟老齐学Python之Python安装,齐学python安装
- 跟老齐学Python之集成开发环境(IDE),齐学python
- 跟老齐学Python之用Python计算,齐学python计算
- 跟老齐学Python之啰嗦的除法,齐学python
- Python基础之函数用法实例详解,python用法实例详解
- python的Template使用指南,pythontemplate
- 一个超级简单的python web程序,pythonweb程序
- python+mysql实现简单的web程序,pythonmysql
- python time模块用法实例详解,pythontime
评论关闭