【廖雪峰Python习题集】列表生成式
来源:互联网 发布:淘宝基础版和智能板 编辑:程序博客网 时间:2024/05/22 08:14
如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错:
>>> [s.lower() for s in L]Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <listcomp>AttributeError: 'int' object has no attribute 'lower'
使用内建的isinstance
函数可以判断一个变量是不是字符串:
>>> x = 'abc'>>> y = 123>>> isinstance(x, str)True>>> isinstance(y, str)False
请修改列表生成式,通过添加if
语句保证列表生成式能正确地执行:
>>> L = ['Hello', 'World', 18, 'Apple', None]>>>[s.lower() for s in L if isinstance(s,str)]
运行结果如下图所示:
阅读全文
0 0
- 【廖雪峰Python习题集】列表生成式
- 【廖雪峰Python习题集】循环
- 【廖雪峰Python习题集】生成器
- 【廖雪峰Python习题集】filter
- 【廖雪峰Python习题集】sorted
- 【廖雪峰Python习题集】数据类型和变量
- 【廖雪峰Python习题集】字符串和编码
- 【廖雪峰Python习题集】条件判断
- 【廖雪峰Python习题集】调用函数
- 【廖雪峰Python习题集】定义函数
- 【廖雪峰Python习题集】map/reduce
- 【廖雪峰Python习题集】使用list和tuple
- 【廖雪峰Python习题集】面向对象高级编程
- 【廖雪峰Python习题集】常用内建模块
- 廖雪峰老师——Python入门( 列表生成式 )
- 廖雪峰python中filter生成素数
- Python练习(廖雪峰)
- 廖雪峰python教程
- Linq 指定的转换无效 ToList()
- 特殊功能寄存器
- 第二章 SQL命令参考-LOAD
- Mac OS 环境下安装ccplot并对CloudSat、CALIPSO和MODIS数据进行可视化
- 机器学习-python编写朴素贝叶斯用于文本分类
- 【廖雪峰Python习题集】列表生成式
- Blog14@linux软件安装:rpm / yum
- 脉冲神经网络之Tempotron简介(一)
- Javascript基础---引用数据类型Array
- JZOJ 5442 荒诞
- JZOJ5441. 【NOIP2017提高A组冲刺11.1】序列
- Java nio&bio的个人看法
- UDP 客户端与服务器端实例
- MatLab视频学习笔记(21世纪电子论坛原创视频)-02