[Python]列表生成式练习

版权声明:本文为博主原创文章,未经博主允许不得转载。@ceezyyy11 https://blog.csdn.net/ceezyyy11/article/details/87894889

[Python]列表生成式练习

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

L = [‘Hello’, ‘World’, 18, ‘Apple’, None]
[s.lower() for s in L]
Traceback (most recent call last):
File “”, line 1, in
File “”, line 1, in
AttributeError: ‘int’ object has no attribute ‘lower’
使用内建的isinstance函数可以判断一个变量是不是字符串:

x = ‘abc’
y = 123
isinstance(x, str)
True
isinstance(y, str)
False
请修改列表生成式,通过添加if语句保证列表生成式能正确地执行:

# -*- coding: utf-8 -*-

L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [i.lower() for i in L1 if isinstance(i,str)]

#test
print(L2)
if L2 == ['hello', 'world', 'apple']:
    print('测试通过!')
else:
    print('测试失败!')


>>> runfile('D:/Programing/Python/person.py', wdir='D:/Programing/Python')
['hello', 'world', 'apple']
测试通过!

列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。

猜你喜欢

转载自blog.csdn.net/ceezyyy11/article/details/87894889
今日推荐