網站首頁 編程語言 正文
list1 = ['火腿腸', '面包', '牛奶', '可樂', '方便面']
1. 添加
# append:在列表尾部添加元素 list1.append('餅干') print(list1)
# 結果:['火腿腸', '面包', '牛奶', '可樂', '方便面', '餅干']?
# insert:在某個索引下插入一個元素 list1.insert(1,'包子') print(list1)
# 結果:['火腿腸', '包子', '面包', '牛奶', '可樂', '方便面']?
# extend:將兩個列表拼接起來 list2=[1,2] list1.extend(list2) print(list1)
# 結果:['火腿腸', '面包', '牛奶', '可樂', '方便面', 1, 2]
2. 刪除
# remove:通過元素的值刪除元素list1.remove('牛奶')print(list1)# 結果:['火腿腸', '面包', '可樂', '方便面']# remove:通過元素的值刪除元素 list1.remove('牛奶') print(list1)
# 結果:['火腿腸', '面包', '可樂', '方便面']?
# pop:通過索引刪除元素,若不填索引則默認刪除最后一個。pop可以將刪除的元素返回 list1.pop(-2) print(list1.pop()) print(list1)
# 結果:
# 方便面
# ['火腿腸', '面包', '牛奶']?
# del:刪除單個元素(功能同pop),刪除多個元素,將整個列表從內存中刪除 del list1[-2] print(list1) # 結果:['火腿腸', '面包', '牛奶', '方便面'] del list1[1:3] print(list1) # 結果:['火腿腸', '可樂', '方便面'] # 連變量名帶內容全部從內存中刪除 del list1
# clear:清空列表,列表還在,但里面每內容 print(list1.clear()) print(list1)
# 結果:
# None
# []
3. 查找/修改
# index:找某個元素的索引,便于對該位置的元素進行修改 print(list1.index('牛奶')) list1[list1.index('牛奶')] = '香蕉牛奶' print(list1)
# 結果:
# 2
# ['火腿腸', '面包', '香蕉牛奶', '可樂', '方便面']?
# count:得到列表中某個元素的出現的次數,返回值為0則表示不存在要查找的元素 print(list1.count('牛奶')) # 結果:1 print(list1.count('橙汁')) # 結果:0
4. 其他
# in 和 not in:判斷某個元素在不在列表中 print('面包' in list1) print('面包' not in list1)
# 結果:
# True
# False?
# reverse:對列表中的元素進行反轉,最后一個元素成為第一個 list1.reverse() print(list1)
# 結果:['方便面', '可樂', '牛奶', '面包', '火腿腸']?
# sort:排序,對于數字默認按照升序排列 list2=[2,4,1,-1,9,22,11,8] list2.sort() print(list2) list2.sort(reverse=True) print(list2)
# 結果:
# [-1, 1, 2, 4, 8, 9, 11, 22]
# [22, 11, 9, 8, 4, 2, 1, -1]?
# copy:復制一個新的列表 list2 = list1.copy() print(list2)
總結
原文鏈接:https://blog.csdn.net/weixin_45633061/article/details/123634431
相關推薦
- 2023-04-06 python判斷列表為空的三種方法總結_python
- 2022-10-25 golang值接收者和指針接收者的區別介紹_Golang
- 2022-03-03 video-time-slider,用于IVR視頻回播的時間選擇插件
- 2023-01-20 C++利用模板實現消息訂閱和分發功能_C 語言
- 2023-04-01 解讀opencv->tensorrt的數據排列方式_python
- 2022-05-12 Kotlin map 高級函數返回新的集合
- 2021-10-25 C語言編寫漢諾塔游戲_C 語言
- 2022-10-29 umi pro-layout : 某個頁面 禁用/移除 pro-layout ( 比如: 登錄頁不需
- 最近更新
-
- 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同步修改后的遠程分支