Lem*_*roy 1 python integer nonetype
我正在使用一行代码来遍历元组列表并将其中的值转换为整数.但是,当我到达一个NoneType元素时,我收到以下错误.
TypeError:int()参数必须是字符串或数字,而不是'NoneType'
我希望能够遍历元组列表并处理NoneTypes.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]
Run Code Online (Sandbox Code Playgroud)
没有最后一个元组,我会得到以下返回:
[(17, 15, 9, 1), (17, 14, 1, 1)]
Run Code Online (Sandbox Code Playgroud)
我理想的回归是:
[(17, 15, 9, 1), (17, 14, 1, 1), (17, 14, None, None)]
Run Code Online (Sandbox Code Playgroud)
任何想法或建议都会非常有帮助.
这应该工作:
tuple_list = [
tuple(int(el) if el is not None else None for el in tup)
for tup in big_tuple
]
Run Code Online (Sandbox Code Playgroud)
我的意思是检查元素是否为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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |