处理整数时遇到 'NoneType' 类型错误
Working past a 'NoneType' Type Error when working with integers
我正在使用一行代码遍历元组列表并将其中的值变成整数。但是,当我到达 None 类型的元素时,出现以下错误。
TypeError: int() argument must be a string or a number, not 'NoneType'
我希望能够遍历元组列表并处理 None 类型。 NoneType 需要保留为 None,因为它需要作为 None.
提交到我的数据库
我想我可能需要做一些 Try 和 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]
我正在使用一行代码遍历元组列表并将其中的值变成整数。但是,当我到达 None 类型的元素时,出现以下错误。
TypeError: int() argument must be a string or a number, not 'NoneType'
我希望能够遍历元组列表并处理 None 类型。 NoneType 需要保留为 None,因为它需要作为 None.
提交到我的数据库我想我可能需要做一些 Try 和 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]