python - 如何在序列中添加每第 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
我的代码的问题是它会一次性追加i
ori*3
的所有值,而不是让n
i 的每个版本都有机会。
解决方案
您可以使用所需的偏移量跨过序列,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')
推荐阅读
- c# - 如何在调试时找到我丢失的值?
- sql - SQL Server 查询侧重于“透视”包含非数字数据的表
- c# - 从 Visual Studio 启动时,Jar 文件控制台窗口快速消失
- javascript - 获取本地时区并将数据库时间转换为它
- scala - 如何用 upickle 读/写一个泛型类
- file - 我们可以在 GCP 存储中创建文件吗?
- java - Hibernate 延迟加载与显式查询
- graphql - 当 GraphiQL 返回数据时,Apollo-react 查询返回 null
- .net-core - Fluent-API 的自定义 DataAnnotations
- c++ - _findnext64 因访问冲突而崩溃