【发布时间】:2020-10-08 11:38:02
【问题描述】:
我有一个巨大的元组列表:
ijs = [(0,1),(0,2),(0,3), (3,2)...]
对于给定值v,我只想获取具有i=v 或j=v 的(i,j) 对(来自存储在ijs 中的所有可能的(i,j) 对)。
例如对于v=0 并给出ijs = [(0,1),(0,2),(0,3), (3,2)],那么我应该返回only_current = [(0,1),(0,2),(0,3)]
示例:
请忽略前 3 行,我在其中构建了一个列表 ijs,其中包含元组。
import numpy as np
# IGNORE THIS PART UNTIL THE MAIN LOOP
N= 1000
indices_upper_triangle = np.triu_indices(N, k = 1) # k=1 above diagonal
i,j = indices_upper_triangle
ijs = [(i,j) for i,j in zip(i,j)] # create (i,j) positions
# MAIN LOOP HERE
# Main loop
all_neig_results = list()
for v in range(N): # for each point
# from all possible (i,j) pairs, get only (i,j) pairs that have either i=v or j=v
only_current = [item for item in ijs if v in item]
all_neig_results.append(only_current)
循环中的列表理解超级慢。
%timeit [item for item in ijs if v in item]
15.9 s ± 361 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
如果我删除检查参数if v in item:
%timeit [item for item in ijs]
1.28 s ± 90.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
如何优化[item for item in ijs if v in item]?
【问题讨论】:
-
尝试使用
np.ma.masked_array?这会比使用 python 列表快得多。 -
感谢您的建议,但我的问题是循环中的列表理解。我会改写我的问题
-
已更新以明确说明我的问题
-
你试过带 lambda 函数的过滤器吗?
-
嗨。不,这会有帮助吗?你能提供一个答案/例子吗?
标签: python list algorithm numpy tuples