Python 迭代两个关键字对象

Python iterrate on two keywords object

背景

我想生成具有分布(np.random.normalnp.random.poisson等)的随机数,传递seveal关键字参数(loc , scale, size,等等每一个都是一个列表)放入其中。

loc = [1, 2, 3, 6, 10]
scale = [4, 6, 7, 8, 5]
size = [10, 9, 7, 8, 5]

# When I know which kwargs is in use, this lambda function works
list(map(lambda x, y: np.random.normal(loc=x, size=y), loc, size))

# however, the number of kwargs may change and the kwargs themselves may change. It won't work with codes below. How to generlize the function above?
list(map(lambda **params: np.random.normal(**params),**{'loc': loc, 'scale': scale, 'size': size}))
list(map(lambda x, y: np.random.poisson(loc=x, size=y), loc, size))

输出:

TypeError                                 Traceback (most recent call last)
<ipython-input-48-1f3449886ea1> in <module>
----> 1 list(map(lambda x, y: np.random.poisson(loc=x, size=y), loc, size))

<ipython-input-48-1f3449886ea1> in <lambda>(x, y)
----> 1 list(map(lambda x, y: np.random.poisson(loc=x, size=y), loc, size))

mtrand.pyx in numpy.random.mtrand.RandomState.poisson()

TypeError: poisson() got an unexpected keyword argument 'loc'

问题

有没有办法使用 built-in/numpy 遍历 kwargs 的元素?

你可以试试这个:

import numpy as np

params = dict(loc=[1,2,3,6,10],
              scale=[4,6,7,8,5],
              size=[10,9,7,8,5])

ds = (dict(zip(params.keys(), vals)) for vals in zip(*params.values()))
list(np.random.normal(**d) for d in ds)

如果你想使用map,你可以这样做:

params = (loc, scale, size)
names = ('loc', 'scale', 'size')

list(map(lambda p: np.random.normal(**dict(zip(names, p))),
         zip(*params)))