使用列表推导,使用随机数填充两个随机长度的数组

时间:2017-06-20 14:28:30

标签: python list-comprehension

正如标题所暗示的那样,我想填充两个单独的列表,每个列表都使用列表理解来拥有它自己的随机长度和内容,类似于:

a, b = [random.randint(1,100), random.randint(1,100) for x in range(random.randrange(1,10))]

可以一行完成吗?如果是这样我将怎么做呢?

谢谢

3 个答案:

答案 0 :(得分:1)

首先,您希望重复两次相同的功能,而不是分别创建两个数组。所以让我们写一个函数random_array

现在,我们可以使用random.choice(range(int))来选择随机数,例如

>>> choice(range(10))
7

或者,我们也可以使用random.randint(0, 10)

>>> random.randint(0, 10)
5

然后,我们可以随机选择N no。使用random.sample给出范围的整数:

>>> n = 5
>>> random.sample(range(10), n)
[3, 2, 1, 9, 4]

所以使用random.samplerandom.choice

>>> from random import sample, choice
>>> def random_array(maxsize, maxint):
...     return sample(range(maxint), choice(range(maxsize)))
... 
>>> random_array(10, 100)
[12, 9, 62, 48, 11, 44, 58, 52, 1]
>>> random_array(10, 100)
[97, 78, 33, 3]

random.randintrandom.sample

>>> from random import randint, sample
>>> def random_array(maxsize, maxint):
...     return sample(range(maxint), randint(0, maxsize))
... 
>>> random_array(10, 100)
[27, 50, 95, 18, 4, 30, 73, 47]

或使用numpy

>>> import numpy as np
>>> np.random.rand() # Random float between 0.0 to 1.0
0.7796560918112618
>>> np.random.rand(2)
array([ 0.75680381,  0.20146147])
>>> np.random.rand(2) # Random array of size 1x2 (column X row)
array([ 0.81612505,  0.42277987])

>>> np.random.rand(random.randint(0, maxsize)) # Random size array of len < maxsize
array([ 0.83846215,  0.77637599,  0.85086381,  0.03674837])
>>> np.random.rand(random.randint(0, maxsize)) # Random size array of len < maxsize
array([ 0.26468399,  0.0472708 ,  0.83615985,  0.20740113,  0.40436625,
        0.84332336,  0.48814732,  0.39267764,  0.30662132])
>>> np.random.rand(random.randint(0, maxsize)) * 100 # Random size array of len < maxsize and max value < 100
array([ 80.85771169,  50.49196633,  21.01646636,  36.15074652,
        97.98209728,  85.68512275,  58.06013557,  23.93219465,
         5.18467685,  12.77761391])

如果你想要一个衬垫:

a =  sample(range(100), choice(range(10)))

答案 1 :(得分:0)

如果您真的想要在一行中创建不同的列表,那么您指的是嵌套列表:

import random

l = [[random.randint(1, 100) for b in range(random.randint(1, 100))] for i in range(2)]

但是,如果您只想要两个单独的列表,那么它将需要两行:

l1 = [random.randint(1, 100) for b in range(random.randint(1, 100))]

l2 = [random.randint(1, 100) for b in range(random.randint(1, 100))]

答案 2 :(得分:0)

让它以这种方式工作

a, b = [random.randint(1,100) for x in range(random.randrange(1,10))], [random.randint(1,100) for x in range(random.randrange(1,10))]

根据上面的一些评论,这可能不是一个好主意。有人在乎解释为什么会这样吗?