[英]Python: duplicating each element in a list
做以下事情的最pythonic方法是什么? 它可以修改舊列表或創建新列表。
oldList = [1, 2, 3, 4]
newList = [1, 1, 2, 2, 3, 3, 4, 4]
使用列表理解 :
>>> oldList = [1, 2, 3, 4]
>>> newList = [x for x in oldList for _ in range(2)]
>>> newList
[1, 1, 2, 2, 3, 3, 4, 4]
上面的列表理解類似於嵌套for循環。
newList = []
for x in oldList:
for _ in range(2):
newList.append(x)
如果你真的喜歡函數式編程:
from itertools import chain,izip
newList = list(chain(*izip(oldList,oldList)))
@falsetru的答案更具可讀性,因此很可能符合“最pythonic”的試金石。
因為沒有人做過修改oldList的答案。 這是一種有趣的方式
>>> oldList = [1, 2, 3, 4]
>>> oldList += oldList
>>> oldList[::2] = oldList[1::2] = oldList[-4:]
>>> oldList
[1, 1, 2, 2, 3, 3, 4, 4]
使用功能概念的另外兩種方法:
>>> list_ = [1,2,3,4]
>>> from itertools import chain
>>> list(chain(*[[x,x] for x in list_]))
[1, 1, 2, 2, 3, 3, 4, 4]
>>> reduce(lambda x,y: x+y, [[x,x] for x in list_])
[1, 1, 2, 2, 3, 3, 4, 4]
一個使用numpy:
list(np.array([[x,x] for x in list_]).flatten())
最后一個列表理解:
[x for y in zip(list_, list_) for x in y]
>>> oldList = [1, 2, 3, 4]
>>> (4*(oldList+[0]+oldList))[::5]
[1, 1, 2, 2, 3, 3, 4, 4]
很奇怪的是
$ python -m timeit -s "oldList = [1, 2, 3, 4]" "[x for x in oldList for _ in range(2)]"
1000000 loops, best of 3: 1.65 usec per loop
$ python -m timeit -s "oldList = [1, 2, 3, 4]" "(4*(oldList+[0]+oldList))[::5]"
1000000 loops, best of 3: 0.995 usec per loop
a=[1,2,3,4]
print a*2
這將打印[1,2,3,4,1,2,3,4]
如果您想要復制元素,可以使用此選項
如果您希望副本位於原始副本旁邊,則可以使用以下代碼
a=[1,2,3,4]
b=[]
for i in range(0,len(a)):
b.append(a[i])
b.append(a[i])
print b
這將打印b = [1,1,2,2,3,3,4,4]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.