python - 有没有更快的方法在 python 中创建配对元素列表?

标签 python list

您好,我在创建 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)

关于python - 有没有更快的方法在 python 中创建配对元素列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63437160/

相关文章:

python - 如何将一个列表的元素添加到另一个没有括号且没有导入的列表中?

python parse 仅打印列表中的第一行

python - 使用 subprocess.call 方法

python - 将以下 PhotoImage 代码行减少到尽可能少的行数

c# - C# 有什么可以与 Python 的列表推导相媲美的吗?

python - 根据端点递归划分列表

.net - 数组与列表<T> : When to use which?

Python 速度 32 vs 64 位 Windows 问题

python - 从 python 文件在 hydra DictConfig 中创建一个新 key

python - 如何将 glob 发现的文件发送到(默认)打印机