Chinaunix首页 | 论坛 | 博客
  • 博客访问: 367051
  • 博文数量: 97
  • 博客积分: 2846
  • 博客等级: 少校
  • 技术积分: 1000
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-19 20:00
文章分类

全部博文(97)

文章存档

2017年(1)

2013年(2)

2012年(6)

2011年(17)

2010年(12)

2009年(41)

2007年(18)

我的朋友

分类: Python/Ruby

2009-04-04 18:56:26

该例子是使用3次循环,分别进行排序,提取最大的,然后删除最大的,再排序,。。。。
或者可以对list进行sort,然后取出最后3个元素。
 
 

# take care if a function modifies a list passed as an argument

def top3(a):
    """Return the 3 highest numbers from the list a"""

    t = []
    for i in xrange(3):
        m = max(a)
        t.append(m)
        a.remove(m)
    return t

grades = [10, 5, 11, 5, 13, 5]
print "Top 3 of the grades %s are:"%grades
print top3(grades)

print "Average grade:", (sum(grades)/len(grades))

# or you can sort the list and extract the last three items

 

文件: top3.rar
大小: 0KB
下载: 下载

阅读(1333) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~