从列表列表中替换列表中的所有元素 [英] Replace all elements in a list from list of lists
问题描述
我有一个列表列表,如果列表中有1个列表充满了nans.
I have a list of lists where 1 of the lists ifs full of nans.
l_of_l=[[1,2,3],[nan,nan,nan],[3,4,5]]
我想用 nans 替换 l_of_l 的列表为零:
I would like to replace the list of the l_of_l with the nans for zeros:
所需的输出是
l_of_l=[[1,2,3],[0,0,0],[3,4,5]]
这是我的代码:
for list1 in l_of_l:
if all(np.isnan(list1)) == True:
list1 = [0] * len(list1)
但是我不确定如何将结果再次分配给l_of_l而不需要生成新的列表列表
However i am not sure on how could I assign the result again to the l_of_l without needing to generate a new list of lists
推荐答案
您可以使用以下列表理解:
You could use the following list comprehension:
import numpy as np
[[0 if np.isnan(j) else j for j in i] for i in l_of_l]
# [[1, 2, 3], [0, 0, 0], [3, 4, 5]]
如果您想避免导入 numpy
,尽管数据表明您应该使用它,则实际上可以执行以下操作:
If you want to avoid importing numpy
, though the data suggests that you should be using it, you could actually do the same with:
[[0 if j!=j else j for j in i] for i in l_of_l]
# [[1, 2, 3], [0, 0, 0], [3, 4, 5]]
根据定义,NaN
永远不等于自己
This works as by definition NaNs
are never equal to themselves
或直接构建一个 numpy
数组并使用 nan_to_num
:
Or directly build a numpy
array and use nan_to_num
:
np.nan_to_num(np.array(l_of_l))
array([[1., 2., 3.],
[0., 0., 0.],
[3., 4., 5.]])
这篇关于从列表列表中替换列表中的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!