这一点很清楚:
a = ['a', 'b', 'c']
x = [v for v in a]
但我不知道该怎么做:
sep = 5
# ??? y = [v + sep for v in a]
print y # expected ['a', 5, 'b', 5, 'c', 5]
如何编写每个源元素包含多个元素的列表推导?
我对此代码的优化不感兴趣:请不要在这些代码中引用[:]
运算符或join
方法或其他内容。我的代码需要列表理解。我目前唯一的选择是4行for
循环,这很不方便:
y = []
for v in a:
y.append(v)
y.append(sep)
答案 0 :(得分:6)
使用嵌套列表理解:
>>> a = ['a','b','c']
>>> [item for x in a for item in (x, 5)]
['a', 5, 'b', 5, 'c', 5]
答案 1 :(得分:5)
您可以先构建list
tuples
,然后使用itertools.chain.from_iterable
展平结果列表:
>>> sep = 5
>>> a = ['a', 'b', 'c']
>>>
>>> import itertools
>>> list(itertools.chain.from_iterable((elem, sep) for elem in a))
['a', 5, 'b', 5, 'c', 5]
答案 2 :(得分:1)
只需使用功能sum()
来展平列表,[[v,sep] for v in a]
将生成[['a', 5], ['b', 5], ['c', 5]]
a = ['a', 'b', 'c']
x = [v for v in a]
sep = 5
y = sum([[v,sep] for v in a],[])
print y
#['a', 5, 'b', 5, 'c', 5]
答案 3 :(得分:1)
这是展示Python的itertool包的强大功能的完美问题
repeat:创建一个对象的无限(或极限)迭代
izip:转换迭代。
chain展开可迭代的
>>> from itertools import izip, chain, repeat
>>> a = ['a', 'b', 'c']
>>> list(chain.from_iterable(izip(a, repeat(5))))
['a', 5, 'b', 5, 'c', 5]
如果你有微观优化的诀窍,你可能有兴趣知道,这比列表理解更快
>>> stmt1 = """
list(chain.from_iterable((elem, 5) for elem in a))
"""
>>> stmt2 = """
list(chain.from_iterable(izip(a, repeat(5))))
"""
>>> timeit.timeit(stmt=stmt1, setup="from __main__ import chain, a", number=100000)
1.3136643729533688
>>> timeit.timeit(stmt=stmt2, setup="from __main__ import chain, izip, repeat, a", number=100000)
0.8959859753707633
>>>
答案 4 :(得分:0)
result = [5 if i % 2 else a[i/2] for i in range(2*len(a))]
(并不是说你应该把这样的代码投入生产)
答案 5 :(得分:0)
>>> a = ['a', 'b', 'c']
>>> [item for sublist in zip(a, [5]*len(a)) for item in sublist]
['a', 5, 'b', 5, 'c', 5]
要打破它:
>>> [5]*len(a)
[5, 5, 5]
>>> zip(a, [5]*len(a))
[('a', 5), ('b', 5), ('c', 5)]
然后使用以下习语展平元组列表:
[item for sublist in l for item in sublist]
使用timeit,这种方法比最快的itertools方法快15%
>>> stmt3 = """
[item for sublist in zip(a, [5]*len(a)) for item in sublist]
"""
>>> timeit.timeit(stmt=stmt3, setup="a = ['a', 'b', 'c']", number=100000)