【问题标题】:Working past a 'NoneType' Type Error when working with integers处理整数时出现“NoneType”类型错误
【发布时间】:2016-04-29 06:31:10
【问题描述】:

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

TypeError: int() 参数必须是字符串或数字,而不是 '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)]

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

【问题讨论】:

    标签: python integer nonetype


    【解决方案1】:

    这应该可行:

    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]
    

    【讨论】:

    • 太好了,我没有意识到你可以集成这样的 if 语句。我习惯于在单独的代码行上编写它。
    • 查看here 以了解int(el) if el is not None else None 语法的解释
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 2019-06-08
    • 1970-01-01
    相关资源
    最近更新 更多