$ python
Python 2.7.3 (default, Sep 26 2013, 20:08:41)
[GCC 4.6.3] on linux2
Type "help"悄中源, "copyright", "credits" or "license" for more information.
>>> import random
>>> a = [random.randint(0, 64) for x in xrange(10)]
>>> a
[43, 30, 23, 60, 11, 3, 24, 42, 46, 60]
前面用random构造随机数列表,模拟原始数据列表a;
下面用sorted - 列表切片得到"找最小的5个值 并存入b数组里面"
>>> b = sorted(a)[:5]
>>> b
[3, 11, 23, 24, 30]
>>>
要注意的是该方式包含重复值,若要“不含重复值”的:
>启态>> a = [random.randint(0, 32) for x in xrange(10)]
>>> a
[4, 0, 26, 17, 28, 25, 17, 4, 27, 19]
>培宏>> sorted(a)[:5]
[0, 4, 4, 17, 17]
>>> b = sorted(set(a))[:5]
>>> b
[0, 4, 17, 19, 25]
>>>
a=[0,1,2,3,4,5,6,7,8,9,10]
a.sort() #从大型戚到小排列搜租掘
a[:5] #切片操作,世核取前5个数