1. 列表基础概念
- 列表:可修改的数据序列,使用方括号
[]创建 - 和元组一样,下标从0开始
breakfast = ["coffee","tea","toast","egg","milk","pork"]Code language: JavaScript (javascript)
2. 访问列表元素(下标索引)
正向索引:从 0 开始
breakfast[0] # 获取第1个元素 → 'coffee'
print(breakfast[1]) # 输出 tea
num = 4
print(breakfast[num]) # num变量充当下标,输出 milkCode language: PHP (php)
获取列表长度 len()
len(breakfast) # 列表有6个元素,返回6
breakfast[5] # 最后一个元素下标 = len(列表)-1
breakfast[len(breakfast)-1]Code language: PHP (php)
负向索引:从末尾倒数
-1:最后1个元素,-2倒数第二个,以此类推
breakfast[-1] # pork
breakfast[-2] # milk
breakfast[-5] # tea
breakfast[-6] # coffeeCode language: CSS (css)
索引越界报错 IndexError: list index out of range
下标超出有效范围就报错:
列表长度为6,有效正向下标:0~5;有效负向下标:-1 ~ -6
breakfast[6] # 报错,最大正向下标是5
breakfast[-7] # 报错,最小负向下标是-6Code language: CSS (css)
提示:遍历列表时,循环下标范围应当是
0 ~ len(list)-1
3. 修改列表元素
列表可变,可以直接通过下标赋值修改原有内容
breakfast[0] = "water"
# 现在第一个元素由 coffee 修改成 waterCode language: PHP (php)
4. 添加元素
append():在末尾添加单个元素
append 会把传入的整体,作为1个元素追加进去
breakfast.append("cookie")
breakfast.append("waffles")Code language: JavaScript (javascript)
注意:
append( [a,b,c] ),会把整个列表当成一个子元素塞进列表,生成嵌套列表!
breakfast.append(["juice", "decaf", "oatmeal"])
# 结果末尾多出一项: ["juice", "decaf", "oatmeal"],列表套列表
# 读取: breakfast[-1][0] → 'juice'Code language: PHP (php)
extend():批量追加多个元素
把传入序列里面每一项拆开,逐个加到列表尾部
breakfast.extend(["juice","decaf","oatmeal"])
# juice、decaf、oatmeal 分别作为独立3个元素追加Code language: CSS (css)
append(x):把x当做一整个元素添加extend(x):把x里面的每一项拆开,逐个追加
示例代码
# 创建列表
breakfast = ["coffee","tea","toast","egg","milk","pork"]
# 正向索引
print(breakfast[0])
print(breakfast[1])
num = 4
print(breakfast[num])
# len获取长度
print(len(breakfast))
print(breakfast[len(breakfast)-1])
# 负索引
print(breakfast[-1])
print(breakfast[-2])
# 修改元素
breakfast[0] = "water"
print(breakfast)
# append添加单个
breakfast.append("cookie")
breakfast.append("waffles")
print(breakfast)
# extend批量添加
breakfast.extend(["juice","decaf","oatmeal"])
print(breakfast)
# append传入列表,产生嵌套列表
breakfast.append(["juice", "decaf", "oatmeal"])
print(breakfast)
print(breakfast[-1][0]) # 读取嵌套列表内部元素Code language: PHP (php)
总结
- 列表
[]是可变;元组()不可变 - 下标从0开始;负索引
-1代表最后一项 - 索引不能越界,否则抛出
IndexError append添加一个整体;extend拆开序列批量添加