5、Python 数据类型详细篇:列表

2022/6/16 1:20:17

本文主要是介绍5、Python 数据类型详细篇:列表,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

在我们的实际开发过程中,列表是一个经常会用到的数据结构,它以占用空间小,浪费内存空间少这一特性而被广泛应用。

什么是列表

列表是一个有序的序列,列表中所有的元素放在 [] 中间,并用逗号分开,例如:

  • [1, 2, 3],一个包含 3 个整数的列表
  • [‘a’, ‘b’, ‘c’],一个包含 3 个字符串的列表

常见运算操作

运算符 +

使用运算符 + 连接列表,示例如下:

>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
>>> [1, 2] + [3, 4] + [5, 6]
[1, 2, 3, 4, 5, 6]

运算符 *

使用运算符 * 将列表的元素重复,示例如下:

>>> [1, 2] * 2
[1, 2, 1, 2]
>>> [1, 2] * 3
[1, 2, 1, 2, 1, 2]

索引 []

通过索引 [] 获取列表中指定位置的元素,示例如下:

>>> x = ['www', 'imooc', 'com']
>>> x[0]
'www'
>>> x[1]
'imooc'
>>> x[2]
'com'
>>> x[-1]
'com'

索引 [:]

在 Python 中,使用语法 列表[start:end],获取列表 列表 中在 [start, end) 范围的子字符串。注意范围 [start, end) 包含 start,不包含 end。举例如下:

>>> x = ['www', 'imooc', 'com']
>>> x[1]
'imooc'
>>> x[2]
'com'
>>> x[1:3]
['imooc', 'com']

关键字 in

通过关键字 in 检查列表中是否包含指定元素,示例如下:

>>> 'imooc' in ['www', 'imooc', 'com']
True
>>> 'mooc' in ['www', 'imooc', 'com']
False

常见函数

len(列表) 函数

使用函数 len 获取列表的长度,示例如下:

>>> len([1, 2, 3])
3
>>> len([1, 2, 3, 4])
4

max(列表) 函数

使用函数 max 获取列表中最大的元素,示例如下:

>>> max([1, 2])
2
>>> max([1, 3, 2])
3

min(列表) 函数

使用函数 min 获取列表中最小的元素,示例如下:

>>> min([1, 2])
1
>>> min([1, 3, 2])
1

常见方法

append(item) 方法

append(item) 方法向列表中新增一个元素 item,示例如下:

>>> x = [1, 2, 3]
>>> x.append(4)
>>> x
[1, 2, 3, 4]

insert(index, item) 方法

insert(index, item) 方法用于将元素 item 插入列表的指定位置,示例如下:

>>> x = ['www', 'com']
>>> x.insert(1, 'imooc')
>>> x
['www', 'imooc', 'com']
>>> x.insert(0, 'http')
>>> x
['http', 'www', 'imooc', 'com']
>>> x.insert(4, 'end')
>>> x
['http', 'www', 'imooc', 'com', 'end']

pop() 方法

pop() 方法从列表的尾部取走一个元素,示例如下:

>>> x = ['www', 'imooc', 'com']
>>> item = x.pop()
>>> item
'com'
>>> x
['www', 'imooc']

remove(item) 方法

remove(item) 方法从列表中删除指定元素 item,示例如下:

>>> x = ['www', 'imooc', 'com']
>>> x.remove('imooc')
>>> x
['www', 'com']

index(item) 方法

index(item) 方法在列表中查找指定元素 item,如果找到元素 item,则返回元素 item 的索引;如果找不到,则抛出异常。示例如下:

>>> x = ['www', 'imooc', 'com']
>>> x.index('imooc')
1
>>> x.index('mooc')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'mooc' is not in list

reverse() 方法

reverse() 方法将列表中元素倒序排列,示例如下:

>>> x = ['www', 'imooc', 'com']
>>> x.reverse()
>>> x
['com', 'imooc', 'www']

sort() 方法

sort() 方法对列表中元素进行排序,示例如下:

>>> x = [1, 3, 2]
>>> x.sort()
[1, 2, 3]
>>> x = [1, 3, 2]
>>> x.sort(reverse = True)
[3, 2, 1]

参考资料

http://www.imooc.com/wiki/pythonlesson1/pythonlist.html



这篇关于5、Python 数据类型详细篇:列表的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程