【问题标题】:python no lambda - sort dictionary on valuepython no lambda - 按值排序字典
【发布时间】:2021-08-25 02:49:12
【问题描述】:

要根据值对字典进行排序,我找到的所有答案都使用 lambda。可以使用函数吗?我似乎无法正确传递值。

sales = {
    'north': 2,
    'south': 6,
    'east': 8,
    'west': 7,
}

def get_value(collection,key):    # substitue for lambda x: x[1]
    return collection.get(key)

print(sales)
#sort_sales = sorted(sales.items(), key=lambda x: x[1])   # uses lambda
sort_sales = sorted(sales.items(), get_value( sales,sales.items() ) )
print(sort_sales)

【问题讨论】:

    标签: python function sorting dictionary key-value


    【解决方案1】:

    看看sales.items() 给你什么。基于此,您可以:

    def get_value(item):
        return item[1]
    
    sorted(sales.items(), key=get_value)
    

    返回

    [('north', 2), ('south', 6), ('west', 7), ('east', 8)]
    

    【讨论】:

    【解决方案2】:

    lambda x: x[1] 的等价物是

    def get_value(x):
        return x[1]
    

    通常,您可以将 lambda 参数列表转换为函数参数列表,并将 lambda 表达式转换为 return 语句,这对于任何非捕获 lambda 都足够了。要捕获 lambda,您需要创建一个嵌套函数来显式捕获所需的变量。

    # (Non-specific example)
    def get_value(foo):
        def _function(x):
            return x[foo]
    
    # If we assume we have a variable foo defined as
    foo = 1
    
    # Then the two are roughly equivalent
    fn1 = get_value(foo)
    fn2 = lambda x: x[foo]
    

    【讨论】:

    • 感谢 Silvio 打破了这一点。出于某种原因,我很困惑为什么 [1] 认为它与排序顺序中的第一个有关。而且我没有看到它是如何变成第二的。它是 collection.items() 列表中每个元素的第 1 个值。
    猜你喜欢
    • 2021-05-01
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 2019-02-08
    • 1970-01-01
    相关资源
    最近更新 更多