在python中重塑矢量与索引

时间:2013-12-03 17:17:54

标签: python sorting vector indexing

我在调整python中的列表时遇到了一些问题。我有一个矢量(A)与-9999999作为一些元素。我想找到那些元素删除它们并删除B中的相应元素。

我试图将非-9999999值编入索引,如下所示:

i = [i for i in range(len(press)) if press[i] !=-9999999]

但是当我尝试使用索引来重塑press和我的其他向量时,我收到错误。 类型错误:列表索引必须是整数,而不是列表

载体的长度为约26000

基本上如果我有矢量A,我想从A中删除-9999999个元素,在B中删除65个。

A = [33,55,-9999999,44,78,22,-9999999,10,34]
B = [22,33,65,87,43,87,32,77,99]

3 个答案:

答案 0 :(得分:2)

由于您提到vector,所以我认为您正在寻找基于NumPy的解决方案:

>>> import numpy as np
>>> a = np.array(A)
>>> b = np.array(B)
>>> b[a!=-9999999]
array([22, 33, 87, 43, 87, 77, 99])

使用itertools.compress的纯Python解决方案:

>>> from itertools import compress
>>> list(compress(B, (x != -9999999 for x in A)))
[22, 33, 87, 43, 87, 77, 99]

时间比较:

>>> A = [33,55,-9999999,44,78,22,-9999999,10,34]*10000
>>> B = [22,33,65,87,43,87,32,77,99]*10000
>>> a = np.array(A)
>>> b = np.array(B)
>>> %timeit b[a!=-9999999]
100 loops, best of 3: 2.78 ms per loop
>>> %timeit list(compress(B, (x != -9999999 for x in A)))
10 loops, best of 3: 22.3 ms per loop

答案 1 :(得分:0)

A = [33,55,-9999999,44,78,22,-9999999,10,34]
B = [22,33,65,87,43,87,32,77,99]
A1, B1 = (list(x) for x in zip(*((a, b) for a, b in zip(A, B) if a != -9999999)))
print(A1)
print(B1)

这会产生:

[33, 55, 44, 78, 22, 10, 34]
[22, 33, 87, 43, 87, 77, 99]

答案 2 :(得分:0)

c = [j for i, j in zip(A, B) if i != -9999999]

zip合并两个列表,创建对列表(x,y)。使用列表推导,您可以过滤A中的-999999元素。