展开列表中的数字

时间:2017-12-03 09:29:32

标签: python list loops numpy

我有一个数字列表:

[10,20,30]

我需要的是根据预定义的增量扩展它。因此,让我们调用x增量和x=2,我的结果应该是:

[10,12,14,16,18,20,22,24,.....,38]

现在我正在使用for循环,但它非常慢,我想知道是否有更快的方法。

编辑:

newA = []
for n in array:
    newA= newA+ generateNewNumbers(n, p, t) 

该函数生成新数字,只需生成要添加到列表中的新数字。

EDIT2: 为了更好地定义问题,第一个数组包含一些时间戳:

[10,20,30]

我有两个参数,一个是采样率,一个是采样时间,我需要的是根据采样率扩展在两个时间戳之间添加正确数量的时间戳的数组。 例如,如果我有一个采样率3和一个采样时间3,结果应为:

[10,13,16,19,20,23,26,29,30,33,36,39]

4 个答案:

答案 0 :(得分:3)

您可以使用np.add.outer为每个时间戳添加相同的增量集,然后使用ravel展平结果。

import numpy as np
a = [10,20,35]
inc = 3
ninc = 4
np.add.outer(a, inc * np.arange(ninc)).ravel()
# array([10, 13, 16, 19, 20, 23, 26, 29, 35, 38, 41, 44])

答案 1 :(得分:1)

你可以使用列表编制,但我不确定我是否理解最后一点包含的停止条件

a = [10, 20, 30, 40]
t = 3
sum([[x for x in range(y, z, t)] for y, z in zip(a[:-1], a[1:])], []) + [a[-1]]

将给出

[10, 13, 16, 19, 20, 23, 26, 29, 30, 33, 36, 39, 40]

答案 2 :(得分:1)

使用rangeitertools.chain

l = [10,20,30]
x = 3
from itertools import chain
list(chain(*[range(i,i+10,x) for i in l]))
#Output:
#[10, 13, 16, 19, 20, 23, 26, 29, 30, 33, 36, 39]

答案 3 :(得分:0)

这里有一堆好的答案。但我会建议numpy和线性插值。

# Now, this will give you the desired result with your first specifications
# And in pure Python too
t = [10, 20, 30]
increment = 2
last = int(round(t[-1]+((t[-1]-t[-2])/float(increment))-1)) # Value of last number in array
# Note if you insist on mathematically "incorrect" endpoint, do:
#last = ((t[-1]+(t[-1]-t[-2])) -((t[-1]-t[-2])/float(increment)))+1
newt = range(t[0], last+1, increment)
# And, of course, this may skip entered values (increment = 3

# But what you should do instead, when you use the samplerate is
# to use linear interpolation
# If you resample the original signal,
# Then you resample the time too
# And don't expand over the existing time
# Because the time doesn't change if you resampled the original properly
# You only get more or less samples at different time points
# But it lasts the same length of time.
# If you do what you originally meant, you actually shift your datapoints in time
# Which is wrong.
import numpy

t = [10, 20, 30, 40, 50, 60]
oldfs = 4000 # 4 KHz samplerate
newfs = 8000 # 8 KHz sample rate (2 times bigger signal and its time axis)
ratio = max(oldfs*1.0, newfs*1.0)/min(newfs, oldfs)
newlen = round(len(t)*ratio)
numpy.interp(
    numpy.linspace(0.0, 1.0, newlen),
    numpy.linspace(0.0, 1.0, len(t)),
    t)

此代码也可以重新采样原始信号(如果有的话)。如果您只是想在两者之间加入更多时间点,您也可以使用插值。再说一次,不要超过现有时间。虽然这个代码可以实现,但与第一个代码兼容。因此,您可以了解自己可以做些什么。

t = [10, 20, 30]
increment = 2
last = t[-1]+((t[-1]-t[-2])/float(increment))-1 # Value of last number in array
t.append(last)
newlen = (t[-1]-t[0])/float(increment)+1 # How many samples we will get in the end
ratio = newlen / len(t)
numpy.interp(
    numpy.linspace(0.0, 1.0, newlen),
    numpy.linspace(0.0, 1.0, len(t)),
    t)

这虽然导致增量为2.5而不是2.但是可以纠正。问题是这种方法适用于浮点时间点和整数。而且很快。如果它们很多,它会变慢,但是直到你达到它们中的很多它会很快起作用。

相关问题