python - 有没有更快的方法在 python 中创建配对元素列表?
问题描述
您好,我在创建 python 列表时遇到了困难。我有数字列表,我想创建对列表,以便该对也是列表,它看起来像这样:[[x0, x1], [x1, x2], ...]
。我已经尝试过列表理解,但对于长列表来说它非常慢。
任何人都可以提出更好(更快)的解决方案吗?
例子:
input = [0.74, 0.72, 0.63, 0.85, 0.75, 0.64] of length 6
output = [[0.74, 0.72], [0.72, 0.63], [0.63, 0.85], [0.85, 0.75], [0.75, 0.64]] of length 5
我试过的:
output = [[x, y] for x, y in zip(input[0:len(input)-1], input[1:len(input)])]
提前致谢!!
解决方案
对于较大的数组长度,请使用NumPy
:
import numpy as np
input = [i for i in range(5000)]
np_input = np.array(input)
%timeit output = [[x, y] for x, y in zip(input[0:len(input)-1], input[1:len(input)])]
# 949 µs ± 35.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit output = np.array([np_input[:-1], np_input[1:]]).reshape(-1, 2)
# 11.5 µs ± 873 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# Answer suggested by @Maryam
%timeit output = np.concatenate((np_input[:-1].reshape(-1,1), np_input[1:].reshape(-1,1)), axis=1)
# 21.9 µs ± 1.17 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
你可以看到output = np.array([np_input[:-1], np_input[1:]]).reshape(-1, 2)
是最快的。
对于较小的数组,请使用您的方法并进行一些更改:
input = [0.74, 0.72, 0.63, 0.85, 0.75, 0.64]
%timeit output = [[x, y] for x, y in zip(input[0:len(input)-1], input[1:len(input)])]
# 2.29 µs ± 46.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit output = [[x, y] for x, y in zip(input[0:], input[1:])]
# 1.92 µs ± 19.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
推荐阅读
- autohotkey - 如何在 Autohotkey 中通过 RegExp 匹配包含键名的字符串
- python - 带有 GUI 的键侦听器脚本不起作用 (Tkinter)
- r - 使用 Gauss-Hermite 求积评估二元正态分布
- deprecated - 在 2019 年 12 月 6 日 Google Drive Android API 关闭后,Games.Snapshots.open 和所有其他已弃用的 Games API 调用是否会继续工作?
- amazon-web-services - 放置存储桶策略时访问被拒绝
- python - 使用两个整数变量之间差异的逻辑
- node.js - 如何使用 emscripten 通过 node.js 进行文件输入?
- .net - XML 使用带有导入的 XSD 进行验证,并包含在 .net 核心中
- python - 如何按整数对元组的混合列表进行排序?
- sql - BigQuery 嵌套表 UPDATE 基于非嵌套数据和嵌套数据的条件