【问题标题】:'NoneType' object has no attribute 'replace' in Python list comprehension“NoneType”对象在 Python 列表理解中没有“替换”属性
【发布时间】:2015-10-09 10:40:05
【问题描述】:

我有以下词典...

mydict = {'columns': ['col1', 'col2', 'col3'],
          'rows': [['col1', 'col2', 'col3'],
                   ['testing data 1', 'testing data 2lk\nIdrjy9dyj', 'testing data 3'],
                   ['testing data 2', 'testing data 3', 'testing data 4'],
                   ['testing data 3', 'testing data 4', 'testing data 5']]}

我正在使用以下列表推导将回车 "\n" 替换为此 "<br>"。它工作正常,除非它在读取 json 文件时传递了一个空字符串。然后它抛出错误'NoneType' object has no attribute 'replace'。我只是不知道如何在列表理解中添加if is not none 语句。任何帮助都非常感谢..

for items in mydict['rows']:
        mydict['rows'][i] = [item.replace("\n","<br>") for item in items]
        i += 1

【问题讨论】:

    标签: json list python-2.7 dictionary nonetype


    【解决方案1】:

    您可以在这里使用布尔表达式:

    [item and item.replace("\n","<br>") for item in items]
    

    如果item 被认为是真的,这只会调用item.replace()None 和空字符串都被认为是错误的。

    如果您想过滤掉任何None 项目,您可以在列表理解中添加一个测试:

    [item.replace("\n","<br>") for item in items if item is not None]
    

    删除None 值或

    [item.replace("\n","<br>") for item in items if item]
    

    只保留非空值。

    【讨论】:

    • 这太棒了!谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 2019-10-03
    • 2021-01-02
    相关资源
    最近更新 更多