将** kwargs更改为Python中的变量

时间:2017-11-29 11:48:41

标签: python python-2.7 keyword-argument

我有一个函数,根据关键字参数('criteria'),将有一个可变数量的附加关键字参数。虽然我可以将这些额外的关键字参数分配给函数的变量,但我想知道是否有任何方法可以根据键和值的关键字参数字典自动创建变量。我的工作测试代码是这样的:

from numpy import nonzero
from numpy.linalg import norm


def subdivide(criteria=None, **kwargs):
    if not criteria:
        raise KeyError
    if criteria == 'curvature':
    k = norm(kwargs['kb'], axis=1)
    k_limit = kwargs['k_limit']
    indices = nonzero((k > k_limit))[0]
    if criteria == 'rotation':
        theta = kwargs['theta']
        theta_limit = kwargs['theta_limit']
        indices = nonzero((theta > theta_limit))[0]
    if criteria == 'rotation & curvature':
        k = norm(kwargs['kb'], axis=1)
        k_limit = kwargs['k_limit']
        theta = kwargs['theta']
        theta_limit = kwargs['theta_limit']
        indices = nonzero((k > k_limit) * (theta > theta_limit))[0]
    return indices

if __name__ == '__main__':
    from numpy.random import rand
    from numpy import array, zeros

    test_kb = array(rand(100, 3))
    theta0 = array(rand(100))
    k0_limit = 1.0
    th_limit = 0.5
    indices = subdivide(criteria='curvature', kb=test_kb, k_limit=k0_limit)
    indices = subdivide(criteria='rotation & curvature', kb=test_kb, 
    theta=theta0, k_limit=k0_limit, theta_limit=th_limit)

我希望能够在评估条件之前有一个通用代码片段,这样我就不必将关键字显式地分配给每个if语句中的变量。类似的东西:

for key, value in kwargs:
   ... make key variable, assign value to key

0 个答案:

没有答案