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