繁体   English   中英

Python列表理解查询

[英]Python list comprehension query

result = ['袁惟仁', None, 'Life']
# Replace None with empty string
response = ['' if s is None else s for s in result]
# Handle non-ascii characters
return [s.encode('utf-8') if isinstance(s, unicode) else str(s) for s in response]

在这段代码中,我用''替换list的None值,然后处理Unicode字符。 这很好,但是想知道是否有更好的方法。 现在,如果我不处理空内容,则会收到一条错误消息,说无法将None转换为str。

使用or使用列表推导表达式可能会得到与以下结果相同的结果:

>>> result = ['袁惟仁', None, 'Life']

>>> [r or '' for r in result]
['\xe8\xa2\x81\xe6\x83\x9f\xe4\xbb\x81', '', 'Life']

顺便说一句,我不明白为什么你要显式地执行.encode('utf-8')

filter(None, result)将从列表中删除所有None

filter(None, result)
['\xe8\xa2\x81\xe6\x83\x9f\xe4\xbb\x81', 'Life']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM