使用两个列表查找特定区间内元素数量的最快方法

问题描述 投票:0回答:1

我有两个列表,称为间隔和时间。对于间隔中的每个 t,我定义了一个间隔(t-dt/2 和 t+dt/2),我想计算 TIME 中有多少元素落入该间隔。基本上我所做的是计算时间段。下面的代码是这样做的,但我有一个问题。

counts = []
for t in intervals:
    # Define time interval bounds
    lower_bound = t - dt / 2
    upper_bound = t + dt / 2
    # Count number of elements in TIME that fall within interval
    count = np.sum(np.logical_and(TIME > lower_bound, TIME < upper_bound)) # Counts the true
    counts.append(count)

这会生成布尔列表并计算数字。但是,我需要一个数值,我还需要将数字除以 list3[n],其中 n 是真正返回的对应值。

例如,如果 TIME[n] > lower_bound,TIME[n] < upper_bound, I just don't want to be counted as 1, but I also want to divide it by list3[n].

我不确定如何在这里实现它,或者是否有更快的方法来实现它。使用蛮力需要花费很多时间,因为这些列表非常大。这是我能找到的最快的,但现在我不知道如何将每个相应的真实回报除以相应的 list3[n]。感谢您的帮助!

python python-3.x performance optimization list-comprehension
1个回答
0
投票

这可以使用 np.where 轻松完成

reciprocal_list3 = 1/list3  # do this line outside of the loop
count = np.sum(np.where(np.logical_and(TIME > lower_bound, TIME < upper_bound), reciprocal_list3, 0))

简单地说,只要比较的逻辑值为

True
,它就会从reciprocal_list3中抓取相同的索引用于求和。

你可能想使用`

© www.soinside.com 2019 - 2024. All rights reserved.