Python【列表函数&方法】
文章目录
- Python【列表函数&方法】
- 列表函数
- 1.len()
- 2.max() min()
- 3.list()
- 列表方法
- 1.append()
- 2.count()
- 3.extend()
- 4.index()
- 5.insert()
- 6.pop()
- 7.remove
- 8.reverse()
- 9.sort()
- 10.clear()
- 11.copy()
列表函数
1.len()
len()可以得到列表的元素个数
x = [1,2,3,4,5,6,7,8]
print(len(x))
输出:
8
2.max() min()
使用max() min()方法可以得到列表中最大的元素和最小的元素:
x = [1,250,30,401,525,65,78,89]
print(max(x))
print(min(x))
输出:
525
1
3.list()
list()方法可以将元组转换为列表:
x = (1,250,30,401,525,65,78,89)
x = list(x)
print(x)
输出:
[1, 250, 30, 401, 525, 65, 78, 89]
列表方法
1.append()
append方法可以在列表末尾添加新的对象
x = [1,2,3,4,5,6,7,8]
x.append(9)
print(x)
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
2.count()
count()方法用于统计某个元素在列表中出现的次数:
x = [1,2,2,2,5,2,7,8]
print(x.count(2))
print(x.count(9))
输出:
4
0
3.extend()
extend()方法可以在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
x = [1,2,2,2,5,2,7,8]
x.extend([1,2,3])
print(x)
输出:
[1, 2, 2, 2, 5, 2, 7, 8, 1, 2, 3]
4.index()
index()方法从列表中找出某个值第一个匹配项的索引位置:
list.index(x,start,end)
- list是查找的列表
- x是查找的目标值
- start可选,是查找的起始位置
- end可选,是查找的结束位置(不包含)
x = [1,2,3,4,5,2,2,8]
print(x.index(2))
print(x.index(2,1))
print(x.index(2,2))
print(x.index(2,2,6))
输出:
1
1
5
5
5.insert()
insert()方法可以将指定对象插入列表的指定位置。
list.insert(index,obj)
- list为要操作的列表
- index为需要插入的索引位置
- obj为要插入的对象
x = [1,2,3,4,5,2,2,8]
x.insert(2,888)
print(x)
输出:
[1, 2, 888, 3, 4, 5, 2, 2, 8]
6.pop()
pop()方法用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
x = ['hello','python','world','apple']
print(x.pop())
print(x)
print(x.pop(1))
print(x)
apple
['hello', 'python', 'world']
python
['hello', 'world']
7.remove
remove()方法可以用于移除列表中某个值的第一个匹配项:
x = ['hello','python','world','apple','world']
x.remove('world')
print(x)
输出:
['hello', 'python', 'apple', 'world']
8.reverse()
reverse()方法用于反向列表中的元素:
x = ['hello','python','world','apple','world']
x.reverse()
print(x)
输出:
['world', 'apple', 'world', 'python', 'hello']
9.sort()
sort()函数用于对原俩表进行排序,如果指定参数,则使用比较函数指定的比较函数。
list.sort(key=None,reverse=False)
- list为要进行排序的列表
- key主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
- reverse是排序规则,reverse=True是降序排序,reverse=False是升序排序
x = [3,5,7,9,1,2,3]
x.sort()
print(x)
x.sort(reverse=True)
print(x)
输出:
[1, 2, 3, 3, 5, 7, 9]
[9, 7, 5, 3, 3, 2, 1]
使用key指定排序参数:
x = [[1,2,9],[2,5,8],[1,1,10],[9,9,1]]
def cmp(it):
return it[2]
x.sort(key=cmp)
print(x)
x.sort(key=cmp,reverse=True)
print(x)
输出:
[[9, 9, 1], [2, 5, 8], [1, 2, 9], [1, 1, 10]]
[[1, 1, 10], [1, 2, 9], [2, 5, 8], [9, 9, 1]]
10.clear()
clear()方法用于清空列表,和del list[:]的效果相同
x = [[1,2,9],[2,5,8],[1,1,10],[9,9,1]]
y = [[1,2,9],[2,5,8],[1,1,10],[9,9,1]]
x.clear()
print(x)
del y[:]
print(y)
输出:
[]
[]
11.copy()
copy()方法用于复制列表,类似于a[:]
x = [[1,2,9],[2,5,8],[1,1,10],[9,9,1]]
a = x.copy()
print(a)
b = x[:]
print(b)
输出:
[[1, 2, 9], [2, 5, 8], [1, 1, 10], [9, 9, 1]]
[[1, 2, 9], [2, 5, 8], [1, 1, 10], [9, 9, 1]]