列表理解问题
有没有办法在每次迭代的列表理解中将多个项目添加到列表中?例如:
y = ['a', 'b', 'c', 'd']
x = [1,2,3]
return [x, a for a in y]
输出:[[1,2,3], 'a', [1,2,3], 'b', [1,2,3], 'c', [1,2, 3], 'd']
Is there a way to add multiple items to a list in a list comprehension per iteration? For example:
y = ['a', 'b', 'c', 'd']
x = [1,2,3]
return [x, a for a in y]
output: [[1,2,3], 'a', [1,2,3], 'b', [1,2,3], 'c', [1,2,3], 'd']
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然有,但不是简单的列表理解:
编辑:受到另一个答案的启发:
它是如何工作的:sum会添加一系列的东西,只要有一个
__add__
成员来完成这项工作。但是,它的初始总数为 0。您无法将 0 添加到列表中,但可以为sum()
提供另一个起始值。这里我们使用一个空列表。如果您不需要一个实际的列表,而只需要一个生成器,则可以使用itertools.chain.from_iterable,它只是将一堆迭代器串成一个长迭代器。
或者对 itertools 更友好:
当然,还有其他方法:首先,我们可以改进 Adam Rosenfield 的 通过消除不需要的 lambda 表达式来回答:
因为 list 已经有一个成员可以完全满足我们的需要。我们可以使用
map
和list.extend
中的副作用来实现相同的效果:最后,让我们尝试尽可能不优雅的纯列表理解:
sure there is, but not with a plain list comprehension:
EDIT: Inspired by another answer:
How it works: sum will add a sequence of anythings, so long as there is a
__add__
member to do the work. BUT, it starts of with an initial total of 0. You can't add 0 to a list, but you can givesum()
another starting value. Here we use an empty list.If, instead of needing an actual list, you wanted just a generator, you can use
itertools.chain.from_iterable
, which just strings a bunch of iterators into one long iterator.or an even more itertools friendly:
There are other ways, too, of course: To start with, we can improve Adam Rosenfield's answer by eliminating an unneeded lambda expression:
since list already has a member that does exactly what we need. We could achieve the same using
map
and side effects inlist.extend
:Finally, lets go for a pure list comprehension that is as inelegant as possible:
这是一种方法:
Here's one way:
(正确的值将在 z 中)
(The correct value will be in z)