python - 在 Python 中使用 map 函数迭代字典列表中的值

标签 python list sorting dictionary list-comprehension

我一直在尝试处理存储在字典列表中的数据,并将其存储在另一个元组列表中。例如说我有以下数据:

triangles= [{"name": "triangle1", "base":3, "height":4}, 
            {"name": "triangle2", "base":5, "height":12}, 
            {"name": "triangle3", "base":8, "height":15}
           ]

我想通过以下我无法更改的函数运行所有数据:

def hypotenuse(base, height):
    hyp_sq=base**2+height**2

    return hyp_sq**(1.0/2.0)

理想情况下,在计算完所有数据后,我想根据三角形的斜边长度对三角形进行排序,并返回以下格式的元组列表:

hypotenuse_results=[("triangle1", 5), ("triangle2", 13), ("triangle3", 17)]

我知道我必须将 map() 函数与 sorted() 结合使用,但我不知道如何只传递对应于“base”和“height”键的值。

如果有人能指出我正确的方向,将不胜感激。

谢谢

最佳答案

大约在 1993 年,Python 得到了 lambda、reduce()、filter() 和 map(),这要归功于错过它们并提交了工作补丁的 Lisp 黑客。这些 Lisp 风格的结构在 Python 中被认为有点陌生,特别是在 2000 年引入列表推导之后。所以不,你不需要 map,你可以使用列表推导或生成器表达式。

您可以让您的hypotenuse 函数接受额外的参数并忽略它们:

def hypotenuse(base, height, **kwargs):
    hyp_sq=base**2+height**2
    return hyp_sq**(1.0/2.0)

然后你可以使用列表理解:

hypotenuse_results = [(t['name'], hypotenuse(**t)) for t in triangles]
hypotenuse_results.sort(key=lambda pair: pair[1])

即使对于大的 len(triangles),这也应该表现得足够好。生成器表达式版本为:

unsorted_results = ((t['name'], hypotenuse(**t)) for t in triangles)
hypotenuse_results = sorted(unsorted_results, key=lambda pair: pair[1])

分析这两个解决方案并在此处发布将是一个很好的练习。

thanks. is there a way to this without modifying the hypotenuse function? – canecse

当然!只需用两个参数调用它:

hypotenuse_results = [(t['name'], hypotenuse(t['base'], t['height'])) for t in triangles]
hypotenuse_results.sort(key=lambda pair: pair[1])

请注意,公认的解决方案是分配一个实际的列表并将其丢弃,因此如果您担心内存占用(在 len(triangles)< 时特别有用,您可能希望使用生成器表达式而不是列表理解 很大但始终是一个好习惯):

hypotenuse_results = sorted(
    ((t['name'], hypotenuse(t['base'], t['height'])) for t in triangles), 
    key=lambda x: x[1]
)

关于python - 在 Python 中使用 map 函数迭代字典列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48080245/

相关文章:

c# - FxCop 说我应该返回一个通用列表接口(interface)而不是字节数组。我是不是该?

javascript - 选择.js : How to sort options on values which are integers?

python - 当我在函数/方法中有输入时,我该如何测试它?

python - 将对象列表与自定义键进行比较

java - 简洁、无警告、通用列表声明?

php - 从数组中获取 3 个最低值,PHP

c# - 排序列表 <DateTime> 降序

python - IIS 7.5 上的 Mercurial 和 hgweb - python 错误

python - 将文件句柄传递给 cython 函数

python - 为类执行方法定义