如何使用列表推导在python中扩展列表? [英] How can I use a list comprehension to extend a list in python?

查看:110
本文介绍了如何使用列表推导在python中扩展列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python没有经验,所以我经常写(简化)如下代码:

I'm not experienced in Python, and I often write code that (simplified) looks like this:

accumulationList = []
for x in originalList:
    y = doSomething(x)
    accumulationList.append(y)
return accumulationList

然后,在我的测试通过后,我重构为

Then after my test passes, I refactor to

return [doSomething(x) for x in originalList]

但是假设结果有所不同,我的循环如下所示:

But suppose it turns out a little different, and my loop looks like this:

accumulationList = []
for x in originalList:
    y = doSomething(x)
    accumulationList.extend(y)
return accumulationList

,其中doSomething列表返回一个列表.完成此操作的最Pythonic方法是什么?显然,先前的列表理解将给出列表列表.

where the doSomething list returns a list. What is the most Pythonic way to accomplish this? Obviously, the previous list comprehension would give a list of lists.

推荐答案

列表理解更简单,更简洁:

Much simpler and cleaner with list comprehension:

[y for x in originalList for y in doSomething(x)]

这篇关于如何使用列表推导在python中扩展列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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