【问题标题】:Python iterrate on two keywords objectPython迭代两个关键字对象
【发布时间】:2022-01-15 06:53:22
【问题描述】:

背景

我想生成具有分布的随机数(np.random.normalnp.random.poisson 等),传递 几个 关键字参数(locscalesize 等。每个都是一个列表)。

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 的元素?

【问题讨论】:

    标签: python numpy iteration


    【解决方案1】:

    你可以试试这个:

    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)
    

    【讨论】:

      【解决方案2】:

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

      params = (loc, scale, size)
      names = ('loc', 'scale', 'size')
      
      list(map(lambda p: np.random.normal(**dict(zip(names, p))),
               zip(*params)))
      

      【讨论】:

        猜你喜欢
        • 2019-12-03
        • 2016-06-04
        • 2023-03-07
        • 1970-01-01
        • 2019-08-20
        • 1970-01-01
        • 1970-01-01
        • 2021-10-05
        相关资源
        最近更新 更多