python3_列表生成式

如果list中既包含字符串,又包含整数,由于非字符串类型没有方法,所以列表生成式会报错:

使用内建的isinstance函数可以判断一个变量是不是字符串:

>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str)
True
>>> isinstance(y, str)
False


[x*x for x in range(1,11)]
//列表生成式
L1 = ['Hello', 'World', 18, 'Apple', None]
L2= [s.lower() for s in L1 if isinstance(s,str)]
print(L2)
if L2 == ['hello', 'world', 'apple']:
    print('测试通过haha!')
else:
    print('测试失败!')

猜你喜欢

转载自blog.csdn.net/wsl_cnxw/article/details/82287663
今日推荐