>>> L = ['Hello', 'World', 18, 'Apple', None]
>>> [s.lower() for s in L]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'lower
t = ['Hello', 'World', 18, 'Apple', None]
print [s.lower() if isinstance(s, str) else s for s in t]思考:如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错:...
最新推荐文章于 2022-05-13 08:28:40 发布
本文通过一个简单的Python示例探讨了如何处理包含不同类型元素的列表。具体来说,文章展示了如何将字符串类型的元素转换为小写形式,同时忽略非字符串类型的元素,如整数和None值。此过程涉及使用条件表达式和类型检查来确保只有字符串被转换。
652

被折叠的 条评论
为什么被折叠?



