列表理解和逻辑索引

IMK*_*IMK 8 python list matrix-indexing

慢慢从Matlab过渡到Python ......

我有这份表格清单

list1 = [[1, 2, nan], [3, 7, 8], [1, 1, 1], [10, -1, nan]] 
Run Code Online (Sandbox Code Playgroud)

和另一个具有相同数量项目的列表

list2 = [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

我正在尝试提取list1中不包含任何nan值的元素,以及list2中的相应元素,即结果应为:

list1_clean = [[3, 7, 8], [1, 1, 1]]
list2_clean = [2, 3]
Run Code Online (Sandbox Code Playgroud)

在Matlab中,使用逻辑索引可以轻松完成.

在这里我感觉列表理解某种形式会起作用,但我坚持:

list1_clean = [x for x in list1 if not any(isnan(x))]
Run Code Online (Sandbox Code Playgroud)

这显然对list2毫无用处.

另外,在逻辑索引以下的尝试并没有工作("指数必须是整数,而不是列表")

idx = [any(isnan(x)) for x in list1]
list1_clean = list1[idx]
list2_clean = list2[idx]
Run Code Online (Sandbox Code Playgroud)

我确定这是微不足道的,但我无法理解,帮助赞赏!

Ash*_*ary 6

你可以用zip.

zip 从传递给它的迭代中返回相同索引上的项.

>>> from math import isnan
>>> list1 = [[1, 2, 'nan'], [3, 7, 8], [1, 1, 1], [10, -1,'nan']]
>>> list2 = [1, 2, 3, 4]
>>> out = [(x,y)  for x,y in zip(list1,list2) 
                                         if not any(isnan(float(z)) for z in x)]

>>> out
[([3, 7, 8], 2), ([1, 1, 1], 3)]
Run Code Online (Sandbox Code Playgroud)

现在解压缩out以获得所需的输出:

>>> list1_clean, list2_clean = map(list, zip(*out))
>>> list1_clean
[[3, 7, 8], [1, 1, 1]]
>>> list2_clean
[2, 3]
Run Code Online (Sandbox Code Playgroud)

帮助zip:

>>> print zip.__doc__
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences.  The returned list is truncated
in length to the length of the shortest argument sequence.
Run Code Online (Sandbox Code Playgroud)

itertools.izip如果你想要一个内存有效的解决方案,你可以使用,因为它返回一个迭代器.