首页 > 解决方案 > 如何在序列中添加每第 n 个?

问题描述

如果我有一个清单:

["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

我的代码的问题是它会一次性追加iori*3的所有值,而不是让ni 的每个版本都有机会。

标签: python

解决方案


您可以使用所需的偏移量跨过序列,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通过重塑数组、转置然后再次展平来做类似的事情

>>> 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')

推荐阅读