Skip to main content
 首页 » 编程设计

python之如何追加序列中的第 n 个

2025年05月04日12haluo1

如果我有一个列表:

["a1", "b1", "c1", "a2", "b2", "c2", "a3", "b3", "c3"] 

我想创建一个新列表,例如:

["a1", "a2", "a3", "b1", "b2", "b3", "c1", "c2", "c3"] 

我试图在 for 循环中执行此操作,以便按顺序附加到新列表:

newlist = [] 
for i in oldlist: 
    newlist.append(oldlist[i]) 
    newlist.append(oldlist[2*i]) 
    newlist.append(oldlist[3*i]) 
    i+3 

我的代码的问题是它会一次性附加 i 或 i*3 的所有值,而不是让每个 n我有机会的第一个版本。

请您参考如下方法:

您可以跨过具有所需偏移量的序列,使用 itertools 展平回一维列表。

>>> import itertools 
>>> d =  ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3'] 
>>> list(itertools.chain.from_iterable([d[::3], d[1::3], d[2::3]])) 
['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3'] 

你也可以使用 numpy 做类似的事情,方法是 reshape 数组,转置,然后再次展平

>>> import numpy as np 
>>> d =  np.array(['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3']) 
>>> np.reshape(d, (d.size//3, 3)).T.flatten() 
array(['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3'], dtype='<U2')