Python loops vs comprehension lists vs map for side effects (i.e. not using return values)

耗尽温柔 提交于 2019-12-01 10:27:23
1.- [r.update(r.pop('some_key')) for r in res if r.get('some_key')]

List Comprehension for side effect is not recommended. It creates a list which is discarded at the end of the operation

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

Not much different from 1 except that, this will break in Py 3.X.

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

Worse then 3. Apart from using map and relying on side effect, you are adding the overhead of a function call

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']

This is better than the rest

  1. No unnecessary List generated that will be discarded
  2. Will work in Py 3.x
  3. No explicit function call overhead

5.- Insert your own approach here

    for r in res:
        if 'some_key' in r:
            r.update(r['some_key'])
            del r['some_key']

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', {}))
  • 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!