繁体   English   中英

使用理解列表一次构建两个列表

[英]build list of lists using comprehension lists two at a time

我使用以下代码来构建列表列表:

res = []
for i in I:
   res.append(x)
   res.append(y[i])

所以我的最终列表是[x, y[0], x, y[1],...]其中xy[i]也是列表。

有没有办法使用列表推导来构建此列表,而不是for循环?

我想......这可能接近你想要的东西:

res = [z for z in ((x, y[i]) for i in I)]

Itertools可以帮助解决这类问题:

>>> y = I = range(5)
>>> x = 'x'
>>> res = list(itertools.chain.from_iterable((x, y[i]) for i in I))
>>> res
['x', 0, 'x', 1, 'x', 2, 'x', 3, 'x', 4]
res = reduce(tuple.__add__,  [(x, y[i]) for i in I])

地图样式:

res = []
map(res.extend, ((x, y[i]) for i in I))

减少风格:

res = reduce(lambda arr, i: arr + [x, y[i]], I, [])
sum(([x, y[i]] for i in I), [])

像bpgergo一样,但是有了列表,并且用一种更简单的方式将它们连接在一起。

我认为这应该做你想要的:

>>> from itertools import chain, izip, repeat
>>> x = [1, 2]
>>> y = [['a', 'b'], ['c', 'd']]
>>> list(chain(*izip(repeat(x), y)))
[[1, 2], ['a', 'b'], [1, 2], ['c', 'd']]

请注意,这将包含内部列表的浅表副本(与其他解决方案相同),因此请确保您了解以下行为:

>>> z = list(chain(*izip(repeat(x), y)))
>>> z
[[1, 2], ['a', 'b'], [1, 2], ['c', 'd']]
>>> x.append(3)
>>> z
[[1, 2, 3], ['a', 'b'], [1, 2, 3], ['c', 'd']]
>>> z[0].append(4)
>>> z
[[1, 2, 3, 4], ['a', 'b'], [1, 2, 3, 4], ['c', 'd']]
>>> y[1].append('e')
>>> z
[[1, 2, 3, 4], ['a', 'b'], [1, 2, 3, 4], ['c', 'd', 'e']]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM