2016-04-29 18 views
1

我正在使用一行代码遍历元组列表并将其中的值设为整数。但是,当我到达一个是NoneType的元素时,出现以下错误。在使用整数时使用'NoneType'类型错误

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

我想能够遍历元组列表并处理NoneTypes。 NoneType需要保留为None,因为它需要以无提交给我的数据库。

我想我可能需要做一些尝试和除了代码,但我不知道从哪里开始。

我使用的代码如下:

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)] 

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

回答

5

这应该工作:

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

我的意思是检查该元素是不是没有,然后才将其转换为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] 
+0

这是伟大的,我不知道,你可以整合一个if语句是这样的。我习惯将它写在单独的代码行上。 – LemusThelroy

+0

@LemusThelroy查看我的更新 – warvariuc

+0

请参阅[这里](https://docs.python.org/2/reference/expressions.html#conditional-expressions)解释'int(el)if el is not None else None '语法 – SiHa

相关问题