我想从列表中做出:
L=[1,2,3,4,5,6,7,8,9]
此:
L=[1,1,1,2,1,3,1,4,1,5,1,6,1,7,1,8,1,9]
这是,将1放在列表中的对象之间。有人能帮助我吗?
答案 0 :(得分:4)
对于您的示例中的结果(每个对象前1):
L = [y for x in L for y in (1, x)]
对于文本描述的结果(对象之间的1):
L = [y for x in L for y in (x, 1)]
L.pop()
如果您在理解中讨厌多个for
条款:
L = list(itertools.chain.from_iterable((1, x) for x in L))
答案 1 :(得分:2)
print ([i for t in zip([1] * len(L), L) for i in t])
<强>输出强>
[1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 8, 1, 9]
答案 2 :(得分:2)
我一直很喜欢切片分配:
>>> L = range(1, 10)
>>> L
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> # Done with setup, let the fun commence!
>>> LL = [None] * (len(L)*2) # Make space for the output
>>> LL[1::2] = L
>>> LL[::2] = [1] * len(L)
>>> LL # Lets check the results, shall we?
[1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 8, 1, 9]
答案 3 :(得分:1)
一个简单的for循环就足够了
for item in list:
newList.append(1)
newList.append(item)
list = newList
答案 4 :(得分:0)
使用itertools:
>>> L=[1,2,3,4,5,6,7,8,9]
>>> from itertools import chain, izip, repeat
>>> list(chain.from_iterable(izip(repeat(1), L)))
[1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 8, 1, 9]