Python列表理解查询

2024-03-28 14:07:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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字符。这很管用,但我想知道是否有更好的方法。现在如果我不处理empty,我会得到一个错误,说不能将None转换为str


Tags: innoneforstringifisresponsewith
2条回答

filter(None, result)将从列表中删除任何None

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

使用or列表理解表达式可以得到相同的结果:

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

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

顺便说一句,我不明白你为什么要显式地做.encode('utf-8')。你知道吗

相关问题 更多 >