Python3 列表
列表的访问、更新、删除、脚本操作符、截取拼接、嵌套与常用函数方法。
访问列表中的值
A list is defined with square brackets and comma-separated items of any type. Use an index for one element and a slice [start:stop:step] for a sub-list — start inclusive, stop exclusive.
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7]
print("list1[0]:", list1[0])
print("list1[-1]:", list1[-1])
print("list2[1:5]:", list2[1:5])
print("list2[:3]:", list2[:3])list1[0]: physics
list1[-1]: 2000
list2[1:5]: [2, 3, 4, 5]
list2[:3]: [1, 2, 3]更新列表
Lists are mutable: assign to an index to replace one item, or assign to a slice to replace a whole range at once (the length may differ).
list1 = ['physics', 'chemistry', 1997, 2000]
print("before:", list1[2])
list1[2] = 2001
print("after :", list1[2])
print(list1)
list1[1:3] = ['math', 2024]
print(list1)before: 1997
after : 2001
['physics', 'chemistry', 2001, 2000]
['physics', 'math', 2024, 2000]删除列表元素
Three common ways to delete: del by position (slices too), remove() deletes the first matching value, pop() removes by position and returns the item.
list1 = ['physics', 'chemistry', 1997, 2000]
print("before:", list1)
del list1[2]
print("del list1[2]:", list1)
list1.remove('chemistry')
print("remove:", list1)
popped = list1.pop()
print("pop:", popped, "->", list1)before: ['physics', 'chemistry', 1997, 2000]
del list1[2]: ['physics', 'chemistry', 2000]
remove: ['physics', 2000]
pop: 2000 -> ['physics']Python 列表脚本操作符
Lists support + concatenation, * repetition, in membership, len(), and for ... in iteration. + returns a new list rather than mutating in place.
| Expression | Result | Description |
|---|---|---|
| len([1, 2, 3]) | 3 | Length |
| [1, 2, 3] + [4, 5, 6] | [1, 2, 3, 4, 5, 6] | Concatenation |
| ['Hi!'] * 4 | ['Hi!', 'Hi!', 'Hi!', 'Hi!'] | Repetition |
| 3 in [1, 2, 3] | True | Membership |
| for x in [1, 2, 3]: print(x) | 1 2 3 | Iteration |
print(len([1, 2, 3]))
print([1, 2, 3] + [4, 5, 6])
print(['Hi!'] * 4)
print(3 in [1, 2, 3])
for x in [1, 2, 3]:
print(x, end=' ')
print()3
[1, 2, 3, 4, 5, 6]
['Hi!', 'Hi!', 'Hi!', 'Hi!']
True
1 2 3Python 列表截取与拼接
Slicing extracts parts: L[2] is the third item, L[-2] the second from the end, L[1:] everything from the second item. Concatenate with += or +.
L = ['Google', 'Runoob', 'Taobao']
print(L[2])
print(L[-2])
print(L[1:])
L += ['Baidu']
print(L)
print(len(L))Taobao
Runoob
['Runoob', 'Taobao']
['Google', 'Runoob', 'Taobao', 'Baidu']
4嵌套列表
List items can themselves be lists, giving 2-D or higher-dimensional structures. Chain indices like x[0][1] to descend level by level.
a = ['a', 'b', 'c']
n = [1, 2, 3]
x = [a, n]
print(x)
print(x[0])
print(x[0][1])
print(x[1][2])[['a', 'b', 'c'], [1, 2, 3]]
['a', 'b', 'c']
b
3列表比较
Lists compare lexicographically element by element. == tests full equality; the operator module offers the same comparisons as functions.
import operator
a = [1, 2]
b = [2, 3]
print(a == b, a != b)
print(a < b, a > b)
print(operator.eq(a, b), operator.lt(a, b))
print([1, 2] == [1, 2], [1, 2] is [1, 2])False True
True False
False True
True FalsePython 列表函数 & 方法
Built-ins len/max/min/sum work on lists; methods append/insert/extend/sort/reverse/count/index/remove/pop/clear mutate in place. sort() returns None — the order lives in the list itself.
nums = [3, 1, 4, 1, 5]
print(len(nums), max(nums), min(nums), sum(nums))
nums.append(9)
nums.insert(0, 0)
print(nums)
nums.sort()
print(nums)
nums.reverse()
print(nums)
print(nums.count(1), nums.index(4))5 5 1 14
[0, 3, 1, 4, 1, 5, 9]
[0, 1, 1, 3, 4, 5, 9]
[9, 5, 4, 3, 1, 1, 0]
2 2sort() sorts in place and returns None. Use sorted(nums) for a new list, and reverse=True for descending order.访问列表中的值
列表用方括号定义,元素以逗号分隔,可以是任意类型且允许混合。用下标取单个元素,用切片 [start:stop:step] 取子列表 —— 切片含头不含尾。
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7]
print("list1[0]:", list1[0])
print("list1[-1]:", list1[-1])
print("list2[1:5]:", list2[1:5])
print("list2[:3]:", list2[:3])list1[0]: physics
list1[-1]: 2000
list2[1:5]: [2, 3, 4, 5]
list2[:3]: [1, 2, 3]更新列表
列表是可变对象,可以直接按下标赋值修改元素;赋值给切片还能一次性替换一段元素,长度可以不同。
list1 = ['physics', 'chemistry', 1997, 2000]
print("before:", list1[2])
list1[2] = 2001
print("after :", list1[2])
print(list1)
list1[1:3] = ['math', 2024]
print(list1)before: 1997
after : 2001
['physics', 'chemistry', 2001, 2000]
['physics', 'math', 2024, 2000]删除列表元素
删除有三种常用方式:del 按位置删(也可删整段切片)、remove() 按值删第一个匹配项、pop() 按位置弹出并返回该元素。
list1 = ['physics', 'chemistry', 1997, 2000]
print("before:", list1)
del list1[2]
print("del list1[2]:", list1)
list1.remove('chemistry')
print("remove:", list1)
popped = list1.pop()
print("pop:", popped, "->", list1)before: ['physics', 'chemistry', 1997, 2000]
del list1[2]: ['physics', 'chemistry', 2000]
remove: ['physics', 2000]
pop: 2000 -> ['physics']Python 列表脚本操作符
列表支持 + 拼接、* 重复、in 成员判断、len() 求长度,以及 for ... in 迭代。注意 + 返回新列表,不会就地修改。
| 表达式 | 结果 | 说明 |
|---|---|---|
| len([1, 2, 3]) | 3 | 长度 |
| [1, 2, 3] + [4, 5, 6] | [1, 2, 3, 4, 5, 6] | 拼接 |
| ['Hi!'] * 4 | ['Hi!', 'Hi!', 'Hi!', 'Hi!'] | 重复 |
| 3 in [1, 2, 3] | True | 元素是否存在于列表中 |
| for x in [1, 2, 3]: print(x) | 1 2 3 | 迭代 |
print(len([1, 2, 3]))
print([1, 2, 3] + [4, 5, 6])
print(['Hi!'] * 4)
print(3 in [1, 2, 3])
for x in [1, 2, 3]:
print(x, end=' ')
print()3
[1, 2, 3, 4, 5, 6]
['Hi!', 'Hi!', 'Hi!', 'Hi!']
True
1 2 3Python 列表截取与拼接
截取用切片,L[2] 取第三个元素,L[-2] 取倒数第二个,L[1:] 取从第二项起的所有元素。拼接用 += 或 +。
L = ['Google', 'Runoob', 'Taobao']
print(L[2])
print(L[-2])
print(L[1:])
L += ['Baidu']
print(L)
print(len(L))Taobao
Runoob
['Runoob', 'Taobao']
['Google', 'Runoob', 'Taobao', 'Baidu']
4嵌套列表
列表的元素本身也可以是列表,形成二维甚至多维结构。用连续下标 x[0][1] 逐层深入访问。
a = ['a', 'b', 'c']
n = [1, 2, 3]
x = [a, n]
print(x)
print(x[0])
print(x[0][1])
print(x[1][2])[['a', 'b', 'c'], [1, 2, 3]]
['a', 'b', 'c']
b
3列表比较
列表按字典序逐元素比较:先比第一个元素,相等则比第二个,依此类推。用 == 判断内容是否完全相同,用 operator 模块可以做函数式比较。
import operator
a = [1, 2]
b = [2, 3]
print(a == b, a != b)
print(a < b, a > b)
print(operator.eq(a, b), operator.lt(a, b))
print([1, 2] == [1, 2], [1, 2] is [1, 2])False True
True False
False True
True FalsePython 列表函数 & 方法
内置函数 len/max/min/sum 直接作用于列表;列表方法 append/insert/extend/sort/reverse/count/index/remove/pop/clear 就地修改。注意 sort() 返回 None,排序结果在列表本身。
nums = [3, 1, 4, 1, 5]
print(len(nums), max(nums), min(nums), sum(nums))
nums.append(9)
nums.insert(0, 0)
print(nums)
nums.sort()
print(nums)
nums.reverse()
print(nums)
print(nums.count(1), nums.index(4))5 5 1 14
[0, 3, 1, 4, 1, 5, 9]
[0, 1, 1, 3, 4, 5, 9]
[9, 5, 4, 3, 1, 1, 0]
2 2sort() 就地排序、返回 None。需要新列表且保留原顺序时用 sorted(nums);reverse=True 可降序。