从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
从传递给它的iterables返回同一索引上的项。现在解压缩
out
以获得所需的输出:有关
zip
的帮助:如果需要一个内存高效的解决方案,可以使用
itertools.izip
,因为它返回一个迭代器。您只需执行以下操作:
从中可以提取每个值:
建议使用
itertools
模块中的izip
,它使用迭代器,可以根据您的问题节省大量内存。代替
~
,您可以使用numpy.logical_not()
,这可能更具可读性。欢迎来到Python!
这应该管用。我们检查一个数字是NaN还是不使用^{} 。
如果原始列表中的元素都不是} 函数,如果iterable的任何元素是
NaN
,我们将元素插入list1_clean
和list2_clean
。为了检查这一点,我们使用^{True
,则返回True
。为了缩小它并避免使用
zip
您可以这样做any
函数->isnan
函数->相关问题 更多 >
编程相关推荐