以下讲解python3中列表函数的用法
python列表操作符
列表对 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表
操作符 | 描述 | 结果 |
---|
['Hi!'] * 4 | 重复 | ['Hi!', 'Hi!', 'Hi!', 'Hi!'] |
[1, 2, 3] + [4, 5, 6] | 组合 | [1, 2, 3, 4, 5, 6] |
3 in [1, 2, 3] | 元素是否存在于列表中 | True |
for x in [1, 2, 3]: print(x, end=" ") | 迭代 | 1 2 3 |
python列表函数用法
序号 | 函数 | 描述 |
---|
1 | len(list) | 列表元素个数 |
2 | max(list) | 返回列表元素最大值 |
3 | min(list) | 返回列表元素最小值 |
4 | list(seq) | 将元组转换为列表 |
5 | list.append(obj) | 在列表末尾添加新的对象 |
6 | list.count(obj) | 统计某个元素在列表中出现的次数 |
7 | list.extend(seq) | 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) |
8 | list.index(obj) | 从列表中找出某个值第一个匹配项的索引位置 |
9 | list.insert(index,obj) | 将对象插入列表 |
10 | list.pop(index=-1) | 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
11 | list.remove(obj) | 移除列表中某个值的第一个匹配项 |
12 | list.reverse() | 反向列表中元素 |
13 | list.sort(key=none,reverse=false) | 对原列表进行排序 |
14 | list.clear() | 清空列表 |
15 | list.copy() | 复制列表 |
列表函数实例如下:
1.len(list)
>>> dpc = [1,2,3]
>>> len(dpc)
3
2.max(list)
>>> dpc = ['a','b','c']
>>> max(dpc)
'c'
3.min(list)
>>> dpc = ['a','b','c']
>>> min(dpc)
'a'
4.list(seq)
>>> str = 'dpc'
>>> list(str)
['d', 'p', 'c']
>>> tuple = (1,2,3)
>>> list(tuple)
[1, 2, 3]
5.list.append(obj
>>> dpc = ['www.baidu.com']
>>> dpc.append('www.dpc.com')
>>> print (dpc)
['www.baidu.com', 'www.dpc.com']
6.list.count(obj)
>>> dpc = ['a','b','a','c']
>>> print (dpc.count('a'))
2
>>> print (dpc.count('b'))
1
>>> print (dpc.count('c'))
1
7.list.extend(seq)
>>> list1 = [1,2,3]
>>> list2 = [4,5,6]
>>> list1.extend(list2)
>>> print (list1)
[1, 2, 3, 4, 5, 6]
8.list.index(obj)
>>> dpc = ['How','are','you']
>>> dpc.index('How')
0
>>> dpc.index('are')
1
>>> dpc.index('you')
2
9.list.insert(index,obj)
参数 | 描述 |
---|
index | 对象obj需要插入的索引位置。 |
obj | 要插入列表中的对象。 |
>>> dpc = [1,2,3]
>>> dpc.insert(3,4)
>>> print (dpc)
[1, 2, 3, 4]
10.list.pop(index=-1)
>>> dpc = ['a','b','c']
>>> dpc.pop()
'c'
>>> dpc.pop(0)
'a'
>>> print (dpc)
['b']
11.list.remove(obj)
>>> dpc = [1,2,3,4]
>>> dpc.remove(2)
>>> print (dpc)
[1, 3, 4]
12.list.reverse()
>>> dpc = [1,2,3,4]
>>> dpc.reverse()
>>> print (dpc)
[4, 3, 2, 1]
13.list.sort(key=none,reverse=false)
参数 | 描述 |
---|
key | 主要是用来进行比较的元素 |
reverse | 排序规则,reverse = True 降序, reverse = False 升序(默认) |
>>> dpc = [1,2,3,4]
>>> dpc.sort(reverse=True)
>>> dpc
[4, 3, 2, 1]
>>> dpc = ['a','b','c']
>>> dpc.sort(reverse=True)
>>> dpc
['c', 'b', 'a']
#int和str同时进行比较会报错
>>> dpc = [1,2,3,'a','b','c']
>>> dpc.sort(reverse=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'