【问题标题】:How to create a function that takes dictionary inputs?如何创建一个接受字典输入的函数?
【发布时间】:2019-12-05 08:07:21
【问题描述】:

我正在为一个项目使用一个模块,我必须将一个函数传递给模块,并且模型会执行以下操作:

class module:
   def __init__(self, function, dictionary):
       # dictionary is {'x':2, 'y':4, 'z':23}
       function(**dictionary)

我的功能是这样的:

def function(*foo):
    return sum(foo)

问题是,模块需要命名变量,并且会像解压字典一样将其传递给函数,而dictionary中的元素数量是可变的,所以我不能将函数预先写成@987654324 @,这会引发错误。我不想修改模块,因为那样的话,代码就不会通用。如何仅通过更改代码来解决此问题?

编辑:我需要 foo 作为在函数中使用的列表

【问题讨论】:

  • __init__ 的第一个参数始终是self。

标签: python python-3.x arguments argument-unpacking


【解决方案1】:

您无法更改的模块正在调用您的函数:

function(**dictionary)

您将无法将您的函数写入参数是一个列表——它没有被传递一个列表。您可以接受关键字作为字典并轻松制作列表。您的函数只需要准备好以这种方式调用:

def f(**foo):

这导致:

class module:
    def __init__(self, function, dictionary):
       # dictionary is {'x':2, 'y':4, 'z':23}
       function(**dictionary)

def f(**foo):
    print(sum(foo.values()))

module(f, {'x':2, 'y':4, 'z':23})

# prints 29 as expected

【讨论】:

    【解决方案2】:
    def function(*args,**Kwargs):
        try:
            return sum(*args)
        else:
            return sum(**kwargs.values())
    

    双 * 解包字典值,一个 * 是解包任何东西(字典除外)。

    【讨论】:

      【解决方案3】:

      参数的数量和类型由函数init的代码决定 在您的情况下,这是字典类型的单个参数。因此,您必须始终传递这样的函数 f(x),其中 x 是字典。 所以就是处理参数的函数 f 。 例如

      def fsum(x): return sum(x.values())
      ...
      __init__(fsum, {'a': 1, 'b': 2, 'c': 3})
      

      【讨论】:

        【解决方案4】:

        您似乎想要值的总和:

           def __init__(self, function, dictionary):
               # dictionary is {'x':2, 'y':4, 'z':23}
               function(dictionary.values())
        

        dictionary.values() 将为您的示例提供[2, 4, 23] 的列表。

        【讨论】:

        • 我觉得你没看懂,我不能编辑模块
        • 那么,module不能改,function可以改吗?
        • 是的,我可以改function
        • 然后查看 Mark Myer 的解决方案
        猜你喜欢
        • 2020-02-24
        • 1970-01-01
        • 2021-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多