【问题标题】:How to use defaultdict to create a dictionary with a lambda function?如何使用 defaultdict 创建带有 lambda 函数的字典?
【发布时间】:2014-09-20 23:45:54
【问题描述】:

我正在尝试使用 lambda 函数创建一个字典,该函数可以根据键中的第二项有条件地插入一个值。

Example:
wts = defaultdict(lambda x: if x[1] == somevalue then 1 else 0)

【问题讨论】:

    标签: python python-2.7 dictionary lambda defaultdict


    【解决方案1】:

    Python 中的conditional expression 看起来像:

    then_expr if condition else else_expr
    

    在你的例子中:

    wts = defaultdict(lambda x: 1 if x[1] == somevalue else 0)
    

    正如 khelwood 在 cmets 中指出的那样,defaultdict 的工厂函数不接受参数。你必须直接覆盖dict.__missing__

    class WTS(dict):
        def __missing__(self, key):
            return 1 if key[1] == somevalue else 0
    
    wts = WTS()
    

    或更具可读性:

    class WTS(dict):
        def __missing__(self, key):
            if key[1] == somevalue:
                return 1
            else:
                return 0
    

    【讨论】:

    • defaultdict 的工厂函数必须采用零参数。所以这是行不通的。
    • key = (A,somevalue) 怎么称呼?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 2022-11-01
    • 2022-12-03
    • 2021-07-14
    • 2017-04-05
    相关资源
    最近更新 更多