具有列表理解的圆形列表值,包括 None

Round list values with list comprehension including None

我想舍入忽略 None 的列表的值。

给定一个没有 None 值的列表,我会这样做:

import math        
value_list = [1.5, 2.3, 3.2, 4.7]
rounded_list = [math.floor(elem) for elem in value_list]

包含 None 个值的列表给出错误:

import math        
value_list = [1.5, 2.3, None, 4.7]
rounded_list = [math.floor(elem) for elem in value_list]
TypeError: must be real number, not NoneType

我有这个解决方案,但我想知道是否有一个单线解决方案

import math 
value_list = [1.5, 2.3, None, 4.7]

for i in range(len(value_list)):
    try:
        value_list[i] = math.floor(value_list[i])
    except:
        pass    

选项 1。舍入值包括 None

rounded_list = [None if elem is None else math.floor(elem) for elem in value_list]

选项 2. 没有 None

的舍入值
rounded_list = [math.floor(elem) for elem in value_list if not elem is None]

您可以像这样为 None 添加检查:

import math        
value_list = [1.5, 2.3, None, 4.7]
rounded_list = [math.floor(elem) for elem in value_list if elem is not None]

print(rounded_list)
>>> [1, 2, 4]

编辑
如果您想保留 None 值,您可以这样做:

import math        
value_list = [1.5, 2.3, None, 4.7]
rounded_list = [math.floor(elem) if elem is not None else None for elem in value_list]

print(rounded_list)
>>> [1, 2, None, 4]
import math

value_list = [1.5, 2.3, None, 4.7]
rounded_list = [None if x is None else math.floor(x) for x in value_list]
print(rounded_list)

打印:

[1, 2, None, 4]