了解列表和逻辑索引

慢慢地从 Matlab 到 Python...

我有这个列表表格


list1 = [[1, 2, nan], [3, 7, 8], [1, 1, 1], [10, -1, nan]]


还有一个包含相同数量的列表


list2 = [1, 2, 3, 4]


我正在尝试提取元素 list1, 不含任何值 nan, 和相应的元素 list2, 即结果应该是:


list1_clean = [[3, 7, 8], [1, 1, 1]]
list2_clean = [2, 3]


在 Matlab 逻辑分度很容易做到。

在这里,我有一种感觉,以某种形式对列表的理解将成为他自己的事业,但我被困在它上:


list1_clean = [x for x in list1 if not any/isnan/x//]


什么明显无用 list2.

或者,以下逻辑索引的尝试不是

在职的 /"索引必须是整数,而不是列表"/


idx = [any/isnan/x// for x in list1]
list1_clean = list1[idx]
list2_clean = list2[idx]


我相信这是痛苦的琐碎,但我无法理解它,帮助我!
已邀请:

八刀丁二

赞同来自:

您可以使用
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/]


现在解压缩
out

, 为了获得必要的结论:


>>> list1_clean, list2_clean = map/list, zip/*out//
>>> list1_clean
[[3, 7, 8], [1, 1, 1]]
>>> list2_clean
[2, 3]


帮助
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.


您可以使用
itertools.izip

, 如果您需要有效的内存解决方案,因为它返回迭代器。

君笑尘

赞同来自:

你可以做到这一点:


ans = [/x,y/ for x,y in zip/list1,list2/ if all/~isnan/x//]

#[/array/[ 3., 7., 8.]/, 2/, /array/[ 1., 1., 1.]/, 3/]


从您可以从哪里提取每个值,使:


l1, l2 = zip/*ans/ 

#l1 = /array/[ 3., 7., 8.]/, array/[ 1., 1., 1.]//
#l2 = /2,3/


建议使用模块
izip


itertools

, 它使用迭代器可以根据您的问题节省大量内存。

反而
~

您可以使用
numpy.logical_not//

, 什么可以更可读。

欢迎来到 Python!

君笑尘

赞同来自:

这应该是工作。 我们检查数字是 NaN 或者不使用
http://docs.python.org/2/libra ... isnan
.

我们插入元素
list1_clean


list2_clean

, 如果源列表中没有任何项目是
NaN

. 要查看它,我们使用该功能
http://docs.python.org/2/libra ... 23any
, 哪个退货
True

, 如果任何迭代迭代相等
True

.


>>> list1 = [[1, 2, float/'NaN'/], [3, 7, 8], [1, 1, 1], [10, -1, float/'NaN'/]]
>>> list2 = [1, 2, 3, 4]
>>> from math import isnan
>>> list1_clean = [elem for elem in list1 if not any/[isnan/element/ for element in elem]/]
>>> list1_clean
[[3, 7, 8], [1, 1, 1]]
>>> list2_clean = [list2[index] for index, elem in enumerate/list1/ if not any/[isnan/element/ for element in elem]/]
>>> list2_clean
[2, 3]


使它更少,避免使用
zip

, 你可能会做,


>>> cleanList = [/elem, list2[index]/ for index, elem in enumerate/list1/ if not any/[isnan/element/ for element in elem]/]
>>> cleanList
[/[3, 7, 8], 2/, /[1, 1, 1], 3/]
>>> list1_clean = [elem[0] for elem in cleanList]
>>> list2_clean = [elem[1] for elem in cleanList]



any

功能 ->


any/.../
any/iterable/ -> bool

Return True if bool/x/ is True for any x in the iterable.



isnan

功能 ->


isnan/.../
isnan/x/ -> bool

Check if float x is not a number /NaN/.

要回复问题请先登录注册