Python3 列表详细介绍
列表是最常用的 Python 数据类型,它可以作为一个方括号内的逗号分隔值出现。
列表的数据项不需要具有相同的类型,创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可。如下所示:
list1 = ['Google', 'XiaoAn', 2025, 2026]
list2 = [1, 2, 3, 4, 5]
list3 = ["a", "b", "c", "d","e","f"]
list4 = ['red', 'green', 'blue', 'yellow', 'white', 'black']
print(list1)
print(list2)
print(list3)
print(list4)访问列表中的值
访问列表中的值可以使用索引来访问,列表索引从 0 开始,第二个索引是 1,依此类推。
list5 = ["a", "b", "c", "d","e","f"]
print(list5[0]) # 输出 a
print(list5[1]) # 输出 b
print(list5[2]) # 输出 c索引也可以从尾部开始,最后一个元素的索引为 -1,往前一位为 -2,以此类推。
list6 = ["a", "b", "c", "d","e","f"]
print(list6[-1]) # 输出 f
print(list6[-2]) # 输出 e
print(list6[-3]) # 输出 d列表截取
除了使用索引来访问列表中的值,也可以使用方括号 [n:m] 的形式截取字符,如下所示:
nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(nums[2:5]) # 输出 30 40 50使用负数索引值截取:
nums2 = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(nums[2:-1]) # 输出 30 40 50, 60,70, 80更新列表
你可以对列表的数据项进行修改或更新,你也可以使用 append() 方法来添加列表项,如下所示:
list1 = ['Google', 'XiaoAn', 2025, 2026]
print ("第三个元素为 : ", list1[2])
list1[2] = 2030
print ( list1[2]) # 输出结果 2030
list2 = ['Google', 'Taobao']
list2.append('Baidu')
print ( list2) #输出结果 ['Google', 'Taobao', 'Baidu']删除列表元素
可以使用 del 删除列表中的元素
list = ['Google', 'XiaoAn', 2026]
print(list) # ['Google', 'XiaoAn', 2026]
del list[2] # 删除第三个元素
print(list) # ['Google', 'XiaoAn']列表操作符
list = ['Google', 'XiaoAn', 2026]
print(len(list)) # 3
list1 = [1,2,3] + [4,5,6]
print(list1) # [1, 2, 3, 4, 5, 6]
list2 = ["ABC"] * 4
print(list2) # ['ABC', 'ABC', 'ABC', 'ABC']
list3 = [1,2,3,4,5,6,7]
print(min(list3)) # 输出 1
print(max(list3)) # 输出 7
print(10 in list3) # False
for x in list3:
print(x)列表方法
list.append 在列表的末尾增加一个元素
list = [1,2,3,4,5,6,7]
list.append(8)
print(list) # [1, 2, 3, 4, 5, 6, 7, 8]list.count 统计某个元素在列表出现的次数
list = [3,2,3,4,5,6,7]
print(list.count(3)) # 2list.extend 使用某个列表扩展列表,相当于一次性增加多个元素
list = [1,2,3,4,5,6,7]
list.extend([9,10])
print(list) # [1, 2, 3, 4, 5, 6, 7, 9, 10]list.index 从列表中找到第一个匹配的索引值
list = [1,2,3,4,5,6,7]
print(list.index(1)) # 0list.pop 移除列表的一个元素,默认最后一个,并且返回这个值
list = [1,2,3,4,5,6,7]
print(list.pop()) # 7
print(list) # [1, 2, 3, 4, 5, 6]list.reverse 将列表的元素的顺序进行反转
list = [1,2,3,4,5,6,7]
list.reverse()
print(list) # [7, 6, 5, 4, 3, 2, 1]list.sort 将列表的元素进行排序
list = [3,2,1,4,5,6,7]
list.sort()
print(list) # [1, 2, 3, 4, 5, 6, 7]list.clear 将列表进行清空
list = [3,2,1,4,5,6,7]
list.clear()
print(list) # []
更新时间:2026-05-26 14:15:34
阅读量:24