Python3 列表

时间:2022-07-25
本文章向大家介绍Python3 列表,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Python3 列表

列表是Python中最基本的数据结构,也是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。列表中的每个元素都分配一个数字 - 那就是它的下标,或者说索引,第一个索引是永远是从0开始,第二个索引是1,依此类推。列表也被称之为序列,和数组的概念有点像,只不过一个列表中可以放不同类型的数据,类似于Java中的Object集合,所以列表的数据项不需要具有相同的类型,并且列表的大小可以自动伸缩,这一点和集合的概念一样的。 创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可。代码示例:

list1 = ['Google', 'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];

与字符串的索引一样,列表索引从0开始。列表可以进行截取、组合等。

访问列表中的值

使用下标索引来访问列表中的值,同样的你也可以使用方括号的形式截取列表中的元素,代码示例:

list1 = ['hello', 'world', 123, 456]
list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

print("list1的第0个下标值是:", list1[0])
print("list2下标0-5以内的值是:", list2[0:5])

运行结果:

 list1的第0个下标值是: hello  list2下标0-5以内的值是: [1, 2, 3, 4, 5]

更新列表

你可以对列表的数据项进行修改或更新,所谓更新就是重新对这个列表中的某个下标赋值,重新赋值后会覆盖原来的值,代码示例:

list1 = ['hello', 'world', 123, 456]

print("list1的第0个下标值为:", list1[0])
list1[0]="你好"
print("更新之后list1的第0个下标值为:", list1[0])

运行结果:

 list1的第0个下标值为: hello  更新之后list1的第0个下标值为: 你好

删除列表元素

可以使用 del 语句来删除列表的的元素,代码示例:

list1 = ['hello', 'world', 123, 456]

print("现在list1中的有元素有:",list1)
del list1[1]
print("删除第1个元素后有:",list1)

运行结果:

 现在list1中的有元素有: [‘你好’, ‘world’, 123, 456]  删除第1个元素后有: [‘你好’, 123, 456]

列表脚本操作符

列表对 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表。

列表截取与拼接代码示例:
list1 = ['hello', 'world', 123, 456]

#截取
print(list1[2])
print(list1[-2])
print(list1[1:])

运行结果:
456
123
[123, 456]

#拼接,只能在python控制台中使用
>>> list1 = ['hello', 'world', 123, 456]
>>> list1+[1, 2, 3, 4, 5, 6, 7, 8, 9]
['hello', 'world', 123, 456, 1, 2, 3, 4, 5, 6, 7, 8, 9]

二维列表

二维列表即是列表中还有列表,使用二维列表即在列表里创建其它列表,下面示例两种常用的二维列表声明方式,代码示例:

list1 = ['hello', 'world', 123, 456]
list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list3 = [list1, list2]
print(list3)

list4 = [['hello', 'world', 123, 456],[1, 2, 3, 4, 5, 6, 7, 8, 9]]
print(list4)

运行结果:

 [[‘hello’, ‘world’, 123, 456], [1, 2, 3, 4, 5, 6, 7, 8, 9]]  [[‘hello’, ‘world’, 123, 456], [1, 2, 3, 4, 5, 6, 7, 8, 9]]

二维列表使用的不多,一般大部分用来做2D游戏的地图

Python列表函数&方法

下面用实际代码演示几个较为常用的方法,代码示例:

list1 = ['hello', 'world', 123, 456, 123, 'hello']
list2 = [45, 12, 78, 56, 3, 2, 48, 78, 156, 45, 1]

list1.append('addObj')
print("在末尾添加了一个新的值:", list1)

list1.insert(2, 'InsertObj')
print("在下标2的位置插入了一个新的值:", list1)

print("123这个值的第一个索引位置:", list1.index(123))

list1.remove('hello')
print("删除了列表中第一个‘hello’:", list1)

list2.sort()
print("排序后的list2:", list2)

list2.reverse()
print("反向排序后的list2:", list2)

list3 = list1.copy()
print("将list1的数据复制到list3中:", list3)

list3.clear()
print("清空list3中的数据:", list3)

运行结果:

 在末尾添加了一个新的值: [‘hello’, ‘world’, 123, 456, 123, ‘hello’, ‘addObj’]  在下标2的位置插入了一个新的值: [‘hello’, ‘world’, ‘InsertObj’, 123, 456, 123, ‘hello’, ‘addObj’]  123这个值的第一个索引位置: 3  删除了列表中第一个‘hello’: [‘world’, ‘InsertObj’, 123, 456, 123, ‘hello’, ‘addObj’]  排序后的list2: [1, 2, 3, 12, 45, 45, 48, 56, 78, 78, 156]  反向排序后的list2: [156, 78, 78, 56, 48, 45, 45, 12, 3, 2, 1]  将list1的数据复制到list3中: [‘world’, ‘InsertObj’, 123, 456, 123, ‘hello’, ‘addObj’]  清空list3中的数据: []