您 能够 使用list-comprehensions和仅内置函数执行此操作,一些怪物如:
>>> result = [ ... random.randint(a,b) ... for args in (((0,50) for _ in range(5)), ((0, 12) for _ in range(2))) ... for a, b in args ... ] >>> result [33, 38, 19, 9, 47, 0, 8]
也许,如果你想使用itertools,你可以这样做:
>>> from itertools import chain, repeat, starmap >>> list(starmap(random.randint, chain(repeat((0,50),5), repeat((0,12),2)))) [16, 47, 40, 21, 15, 12, 4]
这两种方法都难以理解和简单。相反,我个人会选择两个for循环,这是一种天真的方法。它将是高效,简单和可读的。除了showboating,我认为生产代码中的上述方法没有任何优势。
如果您对使用第三方库感到满意,可以通过NumPy:
import numpy as np np.random.seed(0) # for consistency / testing A = np.zeros(7) A[:5] = np.random.randint(0, 20, 5) A[5:] = np.random.randint(0, 12, 2) array([ 12., 15., 0., 3., 3., 7., 9.])
这种方法的好处,即内存预分配,对于更大的阵列将是明显的。
since you want to pick 5 random values from 0 - 50( exclusive) i = 0...4 and then you want to pick 2 random values from 0 - 12( exclusive) i = 5 6
lst = [random.randint(0,50) if i < 5 else random.randint(0,12) for i in range(7)] print(lst) # [7, 10, 40, 4, 38, 1, 5]
import random l = [random.randint(0,50) for i in range(5)] l.extend([random.randint(0,12) for i in range(2)]) print(l)
不要重复使用该名称 list 。一种方法是循环遍历可迭代的边界,并将其发送到 randint
list
randint
from random import randint lst = [randint(*bounds) for bounds in [(0, 50)]*5 + [(0, 12)]*2]
你也可以用 itertools.chain 和 itertools.repeat 避免构建边界列表
itertools.chain
itertools.repeat
lst = [randint(*bounds) for bounds in chain(repeat((0, 50), 5), repeat((0, 12), 2))]