0
点赞
收藏
分享

微信扫一扫

python之列表常用方法

常用方法:

函数名

说明

len(list)

返回列表元素个数

max(list)

返回列表中元素最大值

min(list)

返回列表中元素最小值

list(tup)

将元组转换为列表

list.append(obj)

添加obj对象到列表的末尾

list.count(obj)

返回obj在列表中出现的次数

list..extend(seq)

在列表中添加指定序列(是序列,不单只列表),函数没有返回值。

list.index(x,[start[,end]])

从start位置开始到end结束,查找指定值,并返回该值第一次出现的位置。如果没有找到会报异常。

list.insert(index,obj)

在index位置插入对象obj

list.pop([-1])

删除列表中指定位置的值,并返回该值。默认删除最后一个值。

list.remove(obj)

删除列表中第一次出现的obj对象。(根据值删除)

list.reverse()

将列表中的元素反向排序

list.sort(key=Noen,reverse=False)

将列表中元素排序,key指定用来比较的元素,必须是callable对象;reverse排序规则,True、False

 

extend方法举例:

l1 = ['a','b','ab','d']

# l2 = ['b','ab','c','e']

tup1 = (1,2,3)

l1.extend(tup1)

print(l1)

结果:

['a', 'b', 'ab', 'd', 1, 2, 3]

 

list.index方法举例:

l1 = ['a','b','ab','d','f','ahello']

# l2 = ['b','ab','c','e']

print(l1.index('a',1,5))

结果:

Traceback (most recent call last):

  File "D:/pythonProject/test/test20231218.py", line 3, in <module>

    print(l1.index('a',1,5))

ValueError: 'a' is not in list

 

list.pop方法举例:

l1 = ['a','b','ab','d','f','ahello']

print(l1.pop(2))

print(l1)

结果:

ab

['a', 'b', 'd', 'f', 'ahello']

 

list.sort()方法举例:

l1 = ['a','b','ab','d','f','ahello']

l1.sort(reverse=False)

print(l1)

结果:

['a', 'ab', 'ahello', 'b', 'd', 'f']

 

注意:如果是字符串的话,先比较字符串的第一个字符再比较第二个,按照顺序比较。

 

l1 = ['a',1,'b','ab','d','f','ahello']

l1.sort(reverse=False)

print(l1)

结果:

Traceback (most recent call last):

  File "D:/pythonProject/test/test20231218.py", line 2, in <module>

    l1.sort(reverse=False)

TypeError: '<' not supported between instances of 'int' and 'str'

 

注意:int和string不能用于比较

 

下面是列表中存放的姓名和年龄,指定用年龄排序

def cmpl1(l1in):

    return l1in[1]





l1 = [('zhangsan',12),('lisi',15),('wangwu',10),('zhaoliu',13)]

l1.sort(key=cmpl1)

print(l1)

结果:

[('wangwu', 10), ('zhangsan', 12), ('zhaoliu', 13), ('lisi', 15)]

举报

相关推荐

0 条评论