Skip to main content
 首页 » 编程设计

python之使用整数时遇到 'NoneType' 类型错误

2025年05月04日25kuangbin

我正在使用一行代码遍历元组列表并将其中的值转换为整数。但是,当我到达 NoneType 元素时,我收到以下错误。

TypeError: int() argument must be a string or a number, not 'NoneType'

我希望能够遍历元组列表并处理 NoneTypes。 NoneType 需要保留为 None,因为它需要作为 None 提交到我的数据库。

我想我可能需要做一些 Try and Except 代码,但我不确定从哪里开始。

我使用的代码如下:

big_tuple = [('17', u'15', u'9', u'1'), ('17', u'14', u'1', u'1'), ('17', u'26', None, None)] 
tuple_list = [tuple(int(el) for el in tup) for tup in big_tuple] 

如果没有最后一个元组,我将返回以下内容:

[(17, 15, 9, 1), (17, 14, 1, 1)] 

我理想中想要返回的是:

[(17, 15, 9, 1), (17, 14, 1, 1), (17, 14, None, None)] 

任何想法或建议都会很有帮助。

请您参考如下方法:

这应该有效:

tuple_list = [ 
    tuple(int(el) if el is not None else None for el in tup) 
    for tup in big_tuple 
] 

我的意思是检查元素不是 None,然后才将其转换为 int,否则将 None。

或者你可以创建一个单独的函数来转换元素以使其更具可读性和可测试性:

def to_int(el): 
    return int(el) if el is not None else None 
 
tuple_list = [tuple(map(to_int, tup)) for tup in big_tuple]