苦练Python第21天:列表创建、访问与修改三板斧
前言
大家好,我是倔强青铜三 。是一名热情的软件工程师,我热衷于分享和传播IT技术,致力于通过我的知识和技能推动技术交流与创新,欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!
100 天 Python 挑战迎来 第 21 天 !今天专注最常用也最灵活的数据结构------列表(list),掌握创建、访问、修改全套招式,让你的代码收放自如。
📦 今日收获清单
- 三种创建姿势
- 索引与切片高阶玩法
- 增删改查一步到位
- 嵌套、拷贝、遍历技巧
🔹 1. 创建列表
用 []
一把梭:
python
empty = [] # 空列表
fruits = ["apple", "banana"] # 字符串
info = ["Alice", 30, True] # 混合类型
从可迭代对象直接变列表:
python
list_from_str = list("hello") # ['h','e','l','l','o']
list_from_range = list(range(5)) # [0,1,2,3,4]
🔹 2. 访问元素
索引从 0 开始,负数倒着取:
python
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry
切片一次拿一片:
python
print(fruits[1:3]) # ['banana', 'cherry']
print(fruits[:2]) # ['apple', 'banana']
print(fruits[2:]) # ['cherry']
🔹 3. 修改列表
替换
python
fruits[1] = "blueberry"
追加 & 插入
python
fruits.append("date") # 末尾
fruits.insert(1, "kiwi") # 指定位置
删除
python
fruits.remove("banana") # 按值
fruits.pop() # 末尾弹出
del fruits[0] # 按索引
清空
python
fruits.clear() # 一键归零
🔹 4. 成员与长度
python
if "apple" in fruits:
print("找到了")
print(len(fruits)) # 当前元素个数
🔹 5. 嵌套列表
列表里还能装列表:
python
matrix = [[1, 2], [3, 4]]
print(matrix[1][0]) # 3
🔹 6. 遍历技巧
python
for fruit in fruits:
print(fruit)
# 同时拿索引和值
for idx, fruit in enumerate(fruits):
print(idx, fruit)
🔹 7. 拷贝列表
python
copy1 = fruits.copy()
copy2 = fruits[:] # 切片深拷贝
# 注意:copy = fruits 只是引用
💡 高级提示:万物皆可装
列表可以混装函数、对象、甚至另一个列表:
python
mixed = [42, "hi", [1, 2], True, len]
🧠 一日精华
- 列表有序、可变、允重复
- 创建用
[]
或list()
- 索引、切片、增删改查一条龙
- 嵌套、拷贝、遍历一网打尽
最后感谢阅读!欢迎关注我,微信公众号 :
倔强青铜三
。欢迎点赞
、收藏
、关注
,一键三连!!!