zl程序教程

您现在的位置是:首页 >  Python

当前栏目

Python列表常用的函数和方法(3)_Python自学第二十二节

2023-02-18 16:43:01 时间

pop()、remove()、clear()方法

这三个方法用于删除列表中的元素,都属于原地操作,可以直接对列表进行修改。

pop()方法

pop()方法可以从列表中删除指定的索引的数据,默认是最后一个

>>> a = ['I', 'Love', 'Python', 1, 2, 3]
>>> a.pop(0)   #删除第一个元素‘I’
'I'
>>> a
['Love', 'Python', 1, 2, 3]
>>> a.pop(1)   #删除以上第2个元素‘Python’
'Python'
>>> a
['Love', 1, 2, 3]
>>> a.pop()   #不加索引编号,默认删除最后一个元素
3
>>> a
['Love', 1, 2]

remove()方法

remove()方法可以从列表中删除第一个与指定值相等的元素

>>> protlist = ['I','Love','Python','Beaurse','Python','is','easy']
>>> protlist.remove('Python')
>>> protlist
['I', 'Love', 'Beaurse', 'Python', 'is', 'easy']

clear()方法

clear()方法可以清空列表中的所有数据。

>>> protlist.clear()
>>> protlist
[]

[em]使用pop() 和 remove()方法删除时,如果指定元素不存在,则会抛出异常。[/em]


count()、index()方法

count()方法

count()方法可以统计某元素在列表中出现的次数

>>> protlist = ['I','Love','Python','Beaurse','Python','is','easy']
>>> protlist.count('Python')
2

index()方法

index()方法用于返回指定元素在列表中首次出现的位置

>>> protlist = ['I','Love','Python','Beaurse','Python','is','easy']
>>> protlist.index('Python')
2
>>> protlist.index('Love')
1

测试某元素是否存在于某列表

通过成员测试运算符 in 也可以测试列表中是否存在某个元素。如果列表中不存在指定的元素,则返回False。

>>> 'Python' in protlist   #查看‘Python’是否在protlist列表中存在
True
>>> 'python' in protlist   #查看‘python’是否在protlist列表中存在
False

sort()、reverse()方法

sort()方法

sort()方法可以将列表中的元素进行排序,默认是升序。原地操作。执行完毕修改原列表

>>> a = [1,3,5,2,4,8,7]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5, 7, 8]

reverse()方法

  • reverse()方法可以将列表中的元素顺序颠倒,也就是逆序。类似于[::-1]的效果,但是reverse()方法会修改源列表数据进行原地操作。
  • 利用sort()方法进行降序需要用到reverse参数
>>> a = [1,3,5,2,4,8,7]
>>> a.sort()   #如果不先转换成正序,则直接输出的反转效果
>>> a.reverse()   #正序列表直接转换成逆序列表,实时修改列表内容
>>> a
[8, 7, 5, 4, 3, 2, 1]
>>> a = [1,3,5,2,4,8,7]
>>> a.sort(reverse=True)   #使用reverse=Trun进行降序
>>> a
[8, 7, 5, 4, 3, 2, 1]

sorted()、reversed()函数

通过sorted()和reversed()函数也可以实现正序和逆序,不过这两个函数会生成新的列表,不会对原列表做任何修改。

sorted函数

>>> a = [1,3,5,2,4,8,7]
>>> sorted(a)   #实现正序,但不会改变源列表,而是生成新列表
[1, 2, 3, 4, 5, 7, 8]   #生成了新的列表,不会在源列表进行改变
>>> a
[1, 3, 5, 2, 4, 8, 7]

reversed函数

实现反转效果,与[::-1]效果相同,不进行更改源列表。

>>> a
[1, 3, 5, 2, 4, 8, 7]
>>> reversed(a)   #reversed()函数使生成新的列表

>>> list(reversed(a))   #以列表的形式输出以上对象
[7, 8, 4, 2, 5, 3, 1]

练习

题目链接:https://www.luogu.org/problem/P1427

方法一

#!/usr/bin/python3

a = list(input().split())
a.reverse()
a.pop(0)
print(' '.join(a))

方法二:

#!/usr/bin/python3

a = list(input().split())
a.reverse()
a.remove('0')
print(' '.join(a))