如何从列表列表中删除[NaN]?

时间:2014-02-14 07:16:30

标签: python list python-2.7

我有以下

a = [[u'63764'], [u'63764'], [u'63764'], [u'70272'], [u'98362'], [u'NaN'], [u'NaN']]

如何删除所有[NaN]以获取:

a = [[u'63764'], [u'63764'], [u'63764'], [u'70272'], [u'98362']]

谢谢

1 个答案:

答案 0 :(得分:5)

使用math.isnan检查号码是否为NaN

>>> NaN = float('nan')
>>> import math
>>> math.isnan(1)
False
>>> math.isnan(NaN)
True

list comprehension

>>> [xs for xs in a if not any(math.isnan(x) for x in xs)]
[[1], [1], [2], [2], [2], [3], [3]]

更新根据问题编辑:

>>> a = [[u'63764'], [u'63764'], [u'63764'], [u'70272'], [u'98362'], [u'NaN'], [u'NaN']]
>>> [x for x in a if x != [u'NaN']]
[[u'63764'], [u'63764'], [u'63764'], [u'70272'], [u'98362']]