Remove a tuple containing nan in list of tuples — Python

后端 未结 4 397
心在旅途
心在旅途 2021-01-24 12:13

I have a long list of tuples and want to remove any tuple that has a nan in it using Python.

What I currently have: x = [(\'Recording start\', 0), (nan, 4), (nan, 7

4条回答
  •  一生所求
    2021-01-24 12:45

    You could use list comprehension which checks if any of the items in a tuple is NaN. Check is done by first checking the type and then with math.isnan since it doesn't work for other types:

    import math
    
    x = [('Recording start', 0), (float('nan'), 4), (float('nan'), 7), ('Event marker 1', 150)]
    res = [t for t in x if not any(isinstance(n, float) and math.isnan(n) for n in t)]
    print(res)
    

    Output:

    [('Recording start', 0), ('Event marker 1', 150)]
    

提交回复
热议问题