【发布时间】:2022-02-04 14:28:02
【问题描述】:
我正在尝试从嵌套列表中删除所有 nan 列表项
l1=
[['a', 'b', 'c', 'd', 'e', 'f'],
[1.0, 2.0, 3.0, 4.0, 5.0, nan],
['red', 'orange', 'blue', nan, nan, nan]]
我尝试了以下方法
cleanedList = [x for x in l1 if str(x) != 'nan']
但是,这会返回相同的输出
【问题讨论】:
-
嗨,也许过滤嵌套列表stackoverflow.com/questions/3055358/…
-
您将
nan(可能来自numpy?)与'nan'(这是一个字符串)进行比较,因此两者永远不会匹配并且没有任何内容被过滤掉。 -
没有列表理解:l1= [['a', 'b', 'c', 'd', 'e', 'f'], [1.0, 2.0, 3.0, 4.0, 5.0, nan], ['red', 'orange', 'blue', nan, nan, nan]] cleanList = [] for oldList in l1: newList = [] for val in oldList: 如果 val 不是 nan: newList .append(val) cleanList.append(newList) print(cleanedList)
标签: python