如何使用列表理解来扩展 python 中的列表? [英] How can I use a list comprehension to extend a list in python?

查看:23
本文介绍了如何使用列表理解来扩展 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天全站免登陆