python去除列表中的空值元素实战技巧
作者:chinaherolts2008 时间:2023-12-08 12:16:06
python去除列表中的空值元素实战技巧
产生需求的原因:
最近都在使用python做一些小demo,尤其是经常会用python做一些关于数据处理的操作,于是就产生问题:怎么才能让处理数据时有更好的且直接能上手的案例呢?换言之就是python有什么“奇淫技巧”可以帮助我快速处理数据呢?于是搜集一些案例,结合自己实际工作需要,将这些案例做成连续更新篇,今天来讲一个,即去除列表中的空值元素
需求目标:
搜集针对python高效处理数据的核心代码,今天是实现去除列表中的空值元素
具体实操:
去除列表中的空值元素
关键词:for、while、remove、if
tmp_list = ['支出种类介绍', '三餐', '基金投资', '通信', '借款', '交通出行', '摄影文印', '人情', '', '', '', '', '', '', '', '', '']
# 方法一:
while "" in tmp_list:# 判断是否有空值在列表中
tmp_list.remove("")# 如果有就直接通过remove删除
print(tmp_list)
# 方法二:
new_list = [i for i in tmp_list if i != ""]# 先循环遍历有空值的列表,并抽取非空的列表元素,存储到新的列表中
print(new_list)
结语:
这个是一个连续篇,如果有新的python教程实用案例,会持续更新
补充:python list清理列表中的空元素或特定元素
比较简单的函数,但是很常用,这里记录一下:
功能函数:
def reform_list(check_list):
"""处理列表里的空字符串"""
return [i for i in check_list if (i is not None) and (str(i).strip() != '')]
示例代码
def reform_list(check_list):
"""处理列表里的空字符串"""
return [i for i in check_list if (i is not None) and (str(i).strip() != '')]
if __name__ == '__main__':
my_list = reform_list([1, 2, 3, 4, "", None])
print(my_list)
来源:https://blog.csdn.net/chinaherolts2008/article/details/120058994
标签:python,列表,空值
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
keras和tensorflow使用fit_generator 批次训练操作
2023-04-09 04:55:59
跨浏览器的本地存储(一):userData behavior
2008-08-05 18:13:00
Python中class内置方法__init__与__new__作用与区别解析
2022-12-21 06:00:38
源码编译安装MySQL8.0.20的详细教程
2024-01-22 11:55:52
![](https://img.aspxhome.com/file/2023/5/101355_0s.png)
node实现mock-plugin中间件的方法
2024-05-13 10:05:59
![](https://img.aspxhome.com/file/2023/8/125838_0s.png)
SQLPlus命令操作用法详解
2024-01-27 23:00:18
![](https://img.aspxhome.com/file/2023/9/66549_0s.png)
Python第三方库jieba库与中文分词全面详解
2022-03-14 22:32:40
![](https://img.aspxhome.com/file/2023/4/78614_0s.jpg)
Python爬取腾讯视频评论的思路详解
2021-05-30 23:04:43
![](https://img.aspxhome.com/file/2023/2/70732_0s.jpg)
Python内置方法实现字符串的秘钥加解密(推荐)
2023-10-22 23:45:35
![](https://img.aspxhome.com/file/2023/8/103318_0s.jpg)
在ASP中使用SQL语句之1:SELECT 语句
2007-08-11 12:18:00
python eval 转换k m到乘法计算的操作
2023-10-30 03:26:04
![](https://img.aspxhome.com/file/2023/8/99158_0s.png)
zabbix通过percona插件监控mysql的方法
2024-01-23 04:51:22
![](https://img.aspxhome.com/file/2023/5/93895_0s.png)
PHP模板引擎Smarty中变量的使用方法示例
2023-11-14 23:32:25
Virtualenv 搭建 Py项目运行环境的教程详解
2023-02-22 04:56:33
![](https://img.aspxhome.com/file/2023/5/62625_0s.gif)
Numpy 理解ndarray对象的示例代码
2023-07-17 00:56:20
![](https://img.aspxhome.com/file/2023/7/62607_0s.png)
vue实现一个懒加载的树状表格实例
2023-07-02 17:06:45
![](https://img.aspxhome.com/file/2023/2/139932_0s.png)
在python3环境下的Django中使用MySQL数据库的实例
2021-09-11 13:03:37
![](https://img.aspxhome.com/file/2023/3/67763_0s.png)
javascript一些不错的函数脚本代码
2023-07-02 05:25:52
Python 如何截取字符函数
2023-02-08 11:39:04
浅析C# web访问mysql数据库-整理归纳总结
2024-01-12 17:07:42
![](https://img.aspxhome.com/file/2023/2/84492_0s.png)