Python循环与理解列表vs映射的副作用(即不使用返回值) [英] Python loops vs comprehension lists vs map for side effects (i.e. not using return values)

查看:133
本文介绍了Python循环与理解列表vs映射的副作用(即不使用返回值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL; DR哪个是最好的?

TL;DR Which is the best?

1.- [r.update(r.pop('some_key')) for r in res if r.get('some_key')]

2.- map(lambda r: r.update(r.pop('some_key') if r.get('some_key') else []), res)

3.- map(lambda r: r.update(r.pop('some_key')), filter(lambda r: r.get('some_key'), res))

4.- for r in res:
        if r.get('some_key'):
            for element in r['some_key']:
                r[element] = r['some_key'][element]
            del r['some_key']

5.- Insert your own approach here

注意:这不是生产代码。它是在测试套件中运行的代码,因此我更关心可读性/可维护性而不是性能。然而,我也想知道如果这是生产代码,关于哪个更好的决定(衡量权衡性能/可读性)会改变。

Note : This is not production code. It is code that is run in a test suite, so I am more concerned about legibility/maintainability than performance. Nevertheless I would also like to know if the decision regarding which is better (accounting the tradeoff performance/legibility) would change if this was production code. The number of elements 'some_key' is quite small if this makes a difference.

上下文:我已经阅读了 Python列表解析地图,其中接受的答案说:

Context : I have read Python List Comprehension Vs. Map where the accepted answer says:


[...]列表推导在其他情况下可能更快,所有) pythonistas认为它们更直接和更清晰 [...]。

是Pythonic使用列表推导副作用?说:


非常反对Pythonic这样做 [使用理解只列出副作用的列表,忽略返回值],任何经验丰富的Pythonista会给你一个地狱。中间列表在创建之后丢弃,并且可能非常大,因此创建起来很昂贵。

It is very anti-Pythonic to do so [use comprehension lists for side effects only, ignoring return value], and any seasoned Pythonista will give you hell over it. The intermediate list is thrown away after it is created, and it could potentially be very, very large, and therefore expensive to create.

PS:我已经有一个意见,哪一个是最好的,但我的一个同事不同意。这是为什么我在询问。

PS: I already have an opinion on which one is the best, but one coworker of mine disagrees. This is why I am enquiring.

推荐答案

我认为这个变化对Abhijit的回答,我的第4点是最好的。

I think that this variation on Abhijit answer, which at the same time is a variation of my 4th point is the best.

for r in res:
    r.update(r.pop('some_key', {}))




  • 使用常规 for 循环

  • 很容易理解

  • 只需两行代码

  • 不需要 if 子句

    • Has all the advantages of using a regular for loop
    • Is easy to understand
    • Takes just 2 lines of code
    • Doesn't need the if clause
    • 这篇关于Python循环与理解列表vs映射的副作用(即不使用返回值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆