網站首頁 編程語言 正文
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
相關推薦
- 2022-01-16 npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR!
- 2022-07-26 論網頁檢查preview和response一個是漢字一個是亂碼怎么解決
- 2022-11-17 Android對話框AlertDialog與DatePickerDialog及TimePickerD
- 2023-04-07 解決jest處理es模塊示例詳解_React
- 2022-04-12 詳解pyqt中解決國際化tr()函數不起作用的問題_python
- 2022-11-30 React中常見的TypeScript定義實戰教程_React
- 2022-04-04 微信登陸失敗Error: invalid code
- 2024-02-17 序列轉序模型及其pytorch實現
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支