如何使用列表理解来扩展 python 中的列表?
我在 Python 方面没有经验,我经常编写(简化的)如下所示的代码:
accumulationList = []
for x in originalList:
y = doSomething(x)
accumulationList.append(y)
return accumulationList
然后在测试通过后,我重构为
return [doSomething(x) for x in originalList]
但假设结果有点不同,我的循环如下所示:
accumulationList = []
for x in originalList:
y = doSomething(x)
accumulationList.extend(y)
return accumulationList
其中 doSomething
list 返回一个列表。完成这个任务最Pythonic的方法是什么?显然,前面的列表理解会给出一个列表列表。
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
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用列表理解更简单、更清晰:
Much simpler and cleaner with list comprehension:
你的意思是这样的吗?
或更短的代码(但不是最佳的):
或者相同:
感谢@eyquem的提示(如果使用Python 2.x):
Do you mean something like this?
or shorter code (but not optimal):
or the same:
Thanks to @eyquem for the hint (if using Python 2.x):
我认为涉及 add 或 iadd 的答案在二次时间中运行,这可能不好。我会尝试:
I think the answers involving add or iadd run in quadratic time, which probably isn't good. I'd try:
Python 的就地添加运算符(
+=
,在operator
模块中以iadd
形式提供)相当于.extend
对于列表。将其与reduce
配对以获得您想要的。Python's in-place add operator (
+=
, available asiadd
inoperator
module) is equivalent of.extend
for list. Pair it withreduce
to get what you want.我认为这种情况没有特殊的语法。但是你可以使 for 循环更短:
如果你坚持,你可以使用函数式编程来展平列表:
但我不会称其为 pythonic,我认为它比 for 循环更难阅读。
I don't think there is special syntax for this case. But you could make the for loop shorter:
If you insist, you could use functional programming to flatten the list:
But I wouldn't call this pythonic, I think it's harder to read than a for loop.
功能上,您可以使用
itertools.chain
与地图
。对于输入列表L
:如果您需要迭代器,只需删除
list
调用即可。这是一个演示:Functionally, you can use
itertools.chain
withmap
. For an input listL
:If you need an iterator, simply remove the
list
call. Here's a demo: