- 定义:
[]
- 可存放任意基本数据类型
- 浮点型
- 整型
- 长整型
- 字符串
- 复数
# 随意创建3个列表,同一个列表中可以存放任意基本数据类型
list1 = [3.14, 5.96, 1897, 2020, "China", 3 + 4j]
list2 = [1, 2, 3, 4, 5]
list3 = ["BeiJing", "ShangHai", "NanJing", "GuangZhou"]
list4 = []
- 访问
- 单个访问:坐标,从0开始
- 多个访问:坐标,左闭右开取值
#通过索引下标访问列表中的单个元素
print("list1[2]: ",list1[2])
print("list2[2]: ",list2[2])
print("list3[2]: ",list3[2])
#通过索引下标一次访问多个元素
print("list1[0:2]:",list1[0:2])
执行结果:
list1[2]: 1897
list2[2]: 3
list3[2]: NanJing
list1[0:2]: [3.14, 5.96]
- 更改
list1 = [3.14, 5.96, 1897, 2020, "China", 3 + 4j]
print("before list1[3]: ", list1[3])
list1[3] = "Change"
print("after list1[3]: ", list1[3])
执行结果:
before list1[3]: 2020
after list1[3]: Change
- 删除
- del:坐标
- remove:值
- clear
list1 = [3.14, 5.96, 1897, 2020, "China", 3 + 4j]
print("Before the operation:", list1)
del list1[3]
list1.remove(3 + 4j)
print("After deleting the element:", list1)
list1.clear()
print("After the emptying of the list:", list1)
执行结果:
Before the operation: [3.14, 5.96, 1897, 2020, 'China', (3+4j)]
After deleting the element: [3.14, 5.96, 1897, 'China']
After the emptying of the list: []
- 添加
- append:末尾追加
- insert:插入到该坐标,其他元素后移
list1 = [3.14, 5.96, 1897, 2020, "China", 3 + 4j]
print("before list1: ", list1)
list1.append("New Ele-I")
list1.insert(2, "New Ele-II")
print("after list1: ", list1)
执行结果:
before list1: [3.14, 5.96, 1897, 2020, 'China', (3+4j)]
after list1: [3.14, 5.96, 'New Ele-II', 1897, 2020, 'China', (3+4j), 'New Ele-I']
- 内建方法
- len
- max
- min
- count
- index:第一个匹配项索引
- copy
- reverse
list1 = [2012, 1949, 1897, 2050, 1945, 1949];
#求列表长度,即列表中元素的个数:len(obj)
print("The length of the list: ", len(list1))
#求列表中元素的最大值:max(list)
print("The largest element in the list: ", max(list1))
#求列表中元素的最小值:min(list)
print("The smallest element in the list: ", min(list1))
#统计某个元素在列表中出现的次数:list.count(obj)
print("The number of times 1949 appears: ", list1.count(1949))
#从列表中找出某个值第一个匹配项的索引位置:list.index(obj)
print("The index of the first location of 1949: ", list1.index(1949))
#复制一个已有的表:list.copy()
list2 = list1.copy()
print("list2:", list2)
#反转一个已有的表:list.reverse()
list1.reverse()
print("After reversing :", list1)
执行结果:
The length of the list: 6
The largest element in the list: 2050
The smallest element in the list: 1897
The number of times 1949 appears: 2
The index of the first location of 1949: 1
list2: [2012, 1949, 1897, 2050, 1945, 1949]
After reversing : [1949, 1945, 2050, 1897, 1949, 2012]
- 常用操作
- 拼接
- 乘法
- 迭代
- 嵌套
list1 = [1, 2, 3, 4]
list2 = [5, 6, "BeiJin", 7, 8]
# 列表拼接
print("list1 + list2:", list1 + list2)
# 列表乘法
print("list1*2:", list1 * 2)
# 判断元素是否存在于列表中
print("3 in list1?", 3 in list1)
print("100 in list1?", 100 in list1)
# 迭代
for element in list1:
print(element)
# 列表嵌套
list3 = [list1, list2]
print("list3:", list3)
执行结果:
list1 + list2: [1, 2, 3, 4, 5, 6, 'BeiJin', 7, 8]
list1*2: [1, 2, 3, 4, 1, 2, 3, 4]
3 in list1? True
100 in list1? False
1
2
3
4
list3: [[1, 2, 3, 4], [5, 6, 'BeiJin', 7, 8]]