如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错:
使用内建的isinstance
函数可以判断一个变量是不是字符串:
# -*- coding: utf-8 -*- L1 = ['Hello', 'World', 18, 'Apple', None] L2 = [s.lower() for s in L1 if isinstance(s, str)]
L2 的分解: [s.lower() for s in L1 if isinstance(s,str) ], 便于理解用