首页 > 解决方案 > 有没有更快的方法在 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)])]

提前致谢!!

标签: pythonlist

解决方案


对于较大的数组长度,请使用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)

推荐阅读