python生成随机数组

Python019

python生成随机数组,第1张

从已有数组中提取随机数组

要求:从两个不同数组中随机抽取数组,用到函数np.random.choice

import numpy as np

hyper=[1,2,5,8,9,12,13,14,17,19]

noh=[3,4,6,7,10,11,15,16,18,20]

#h:n 2:2

l1=np.random.choice(hyper,2,replace=False)

l2=np.random.choice(noh,2,replace=False)

ll=[l2[0],l1[0],l1[1],l2[1]]

print(ll)

l1=np.random.choice(hyper,2,replace=False)

l2=np.random.choice(noh,2,replace=False)

ll=[l1[0],l2[0],l1[1],l2[1]]

print(ll)

l1=np.random.choice(hyper,2,replace=False)

l2=np.random.choice(noh,2,replace=False)

ll=[l1[0],l1[1],l2[0],l2[1]]

print(ll)

l1=np.random.choice(hyper,2,replace=False)

l2=np.random.choice(noh,2,replace=False)

ll=[l2[1],l2[0],l1[0],l1[1]]

print(ll)

from random import randint

ar=[[randint(1,100) for _ in range(4)] for _ in range(5)]

print(ar)

$ 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]

>>>