Python中的列表类似于C语言中的数组,下面通过实例说明介绍几种常用的使用方法。
1.空列表的创建
>>> empty=[]
>>> print(empty)
[]
2.列表中元素的查看
>>> words=["a","b","c"]
>>> print(words[2])
c
>>> print(words[3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
3.列表的修改
>>> words=["a",'b',1,2,'3']
>>> words[0]=0
>>> print(words)
[0, 'b', 1, 2, '3']
4.列表的运算
>>> nums=[1,2,3,4,5]
>>> print(nums+[6,7])
[1, 2, 3, 4, 5, 6, 7]
>>> print(nums-[1])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'
>>> print(nums*2)
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
>>> print(nums/2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'list' and 'int'
只能进行加乘,且不会改变原列表中的元素。
5.多列表的组合
>>> words=[1,2,3,[4,'a','b'],5,6]
>>> print(words[1])
2
>>> print(words[3][1])
a
6.列表的检测
>>> words=[1,2,3,[4,'a','b'],5,6]
>>> print('c'in words)
False
>>> print('d' not in words)
True
>>> print(not 'd' in words)
True
主要用于检测某元素是否在该列表中
7.列表中元素的插入
>>> nums=[1,2,3,4,5]
>>> nums.append(0)
>>> print(nums)
[1, 2, 3, 4, 5, 0]
>>> index=4
>>> nums.insert(index,"a")
>>> print(nums)
[1, 2, 3, 4, 'a', 5, 0]
append只能插入列表的尾部,而insert可以插入列表的任何位置
8.列表中某元素的位置
>>> words=['p','y','t','h','o','n']
>>> print(words.index('t'))
2
其他函数我就不一一举例,如下:
len(list):获取列表的长度
max(list):获取列表中的最大值
min(list):获取列表中的最小值
list.remove(x):删除列表中的某个元素
list.count(x):获取列表中某元素出现的次数