一、列表的函数
python列表函数:len(),max(),min(),list(),cmp()
1.len(list)
len()函数是统计列表中有多少元素
lists = [1, 2, 3, 4, 5, 6, 7]
print(len(lists))
# 7
2.max(list)与min(list)
max 与 min 函数返回list中的最大值与最小值
lists = [1, 2, 3, 4, 5, 6, 7]
print(max(lists))
print(min(lists))
# 7 1
3.list(seq)
list()函数可以将其他的数据类型转化成list类型
aTuple = (1, 2, 3, 'abc')
aList = list(aTuple)
print(aList)
# [1, 2, 3, 'abc']
二、列表的方法
1.list.append()
在列表末尾添加新的对象
aList = [1, 2, "abc"]
aList.append(4)
print(aList)
# [1, 2, 'abc', 4]
2.list.append()
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
aList = [1, 2, 3, 'xyz']
bList = [5, 'abc']
aList.extend(bList)
print(aList)
# [1, 2, 3, 'xyz', 5, 'abc']
3.list.insert(index,obj)
将指定对象插入列表的指定位置。
aList = [1, 2, 3, 'xyz']
aList.insert(1,"abc")
print(aList)
# [1, 'abc', 2, 3, 'xyz']
4.list.count()
统计某个元素在列表中出现的次数。
aList = [1, 2, 3, 'xyz', 'xyz']
print(aList.count('xyz'))
# 2
5.list.index()
从列表中找出某个值第一个匹配项的索引位置。
aList = [1, 2, 3, 'xyz', 'xyz']
print(aList.index('xyz'))
# 3
6.list.pop()
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
pop()里面可以指定位置的元素,不指定默认就是最后一个
aList = [1, 2, 3, 'xyz']
aList.pop(3)
print(aList)
# [1, 2, 3]
7.list.remove()
移除列表中某个值的第一个匹配项。
aList = [1, 2, 'xyz', 3, 'xyz']
aList.remove('xyz')
print(aList)
# [1, 2, 3, 'xyz']
8.list.reverse()
反向列表中元素。
aList = [1, 2, 'xyz', 3, 'xyz']
aList.reverse()
print(aList)
# ['xyz', 3, 'xyz', 2, 1]
9.list.sort()
list.sort(cmp=None, key=None, reverse=False),对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数。
cmp:可选参数, 如果指定了该参数会使用该参数的方法进行排序。
key:主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse:排序规则,reverse = True 降序, reverse = False 升序(默认)。
aList = [1, 2, 5, 9, 6]
aList.sort()
print(aList)
# [1, 2, 5, 6, 9]
bList = [1, 2, 5, 9, 6]
bList.sort(reverse=True)
print(bList)
# [9, 6, 5, 2, 1]
三、列表切片截取
list[2] 读取索引为2的元素
list[-2] 读取列表中倒数第二个元素
list[1:] 从索引为1的元素开始截取列表
list[1:3] 从索引1开始取,直到索引3为止,但不包括索引3。
aList = ['Google', 'Runoob', 'Taobao', 'Hello']
print(aList[2])
# Taobao
print(aList[-2])
# Taobao
print(aList[1:])
# ['Runoob', 'Taobao', 'Hello']
print(aList[1:3])
# ['Runoob', 'Taobao']