简体   繁体   中英

Subtracting two lists preserving “None” elements

Is there a pythonic way of subtracting the elements of two lists when the corresponding elements in both lists are different from "None" and placing "None" in the opposite case?

Example:

a = [11, 20, 3, 14, 5]
b = [3, 7, None, None, 0]

a - b = [8, 13, None, None, 5]

Instead of using None, you could use a NaN, which is designed for exactly this sort of purpose. Using None makes operations that contain some arbitrary other value to return that arbitrary other value

import math
a = [11, 20, 3, 14, 5]
b = [3, 7, float('nan'), float('nan'), 0]
c= b[3]-a[1]
print(c)

Result = "nan"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM