Python列表 pop() 是Python中的一个内置函数,用于从 列表 或者给定的索引值。
null
语法:
列出你的名字。流行音乐(索引)
参数:
- 指数 ( 可选择的 )–索引处的值弹出并删除。如果没有给出索引,则弹出并删除最后一个元素。
返回: 列表中的最后一个值或给定的索引值。
例外情况: 当索引超出范围时,它将返回IndexError。
示例1:使用pop()方法
Python3
# Python3 program for pop() method list1 = [ 1 , 2 , 3 , 4 , 5 , 6 ] # Pops and removes the last element from the list print (list1.pop()) # Print list after removing last element print ( "New List after pop : " , list1, "" ) list2 = [ 1 , 2 , 3 , ( 'cat' , 'bat' ), 4 ] # Pop last three element print (list2.pop()) print (list2.pop()) print (list2.pop()) # Print list print ( "New List after pop : " , list2, "" ) |
输出:
6New List after pop : [1, 2, 3, 4, 5] 4('cat', 'bat')3New List after pop : [1, 2]
例2
Python3
# Python3 program showing pop() method # and remaining list after each pop list1 = [ 1 , 2 , 3 , 4 , 5 , 6 ] # Pops and removes the last # element from the list print (list1.pop(), list1) # Pops and removes the 0th index # element from the list print (list1.pop( 0 ), list1) |
输出:
6 [1, 2, 3, 4, 5]1 [2, 3, 4, 5]
例3: 展示 索引器
Python3
# Python3 program for error in pop() method list1 = [ 1 , 2 , 3 , 4 , 5 , 6 ] print (list1.pop( 8 )) |
输出:
Traceback (most recent call last): File "/home/1875538d94d5aecde6edea47b57a2212.py", line 5, in print(list1.pop(8))IndexError: pop index out of range
例4:实例
水果清单包含 水果名 和 所有物 说它的果实。另一个列表包含两项 果汁 和 吃 .在pop()和 附加() 我们可以做一些有趣的事。
Python3
# Python3 program demonstrating # practical use of list pop() fruit = [[ 'Orange' , 'Fruit' ],[ 'Banana' , 'Fruit' ], [ 'Mango' , 'Fruit' ]] consume = [ 'Juice' , 'Eat' ] possible = [] # Iterating item in list fruit for item in fruit : # Inerating use in list consume for use in consume : item.append(use) possible.append(item[:]) item.pop( - 1 ) print (possible) |
输出:
[['Orange', 'Fruit', 'Juice'], ['Orange', 'Fruit', 'Eat'], ['Banana', 'Fruit', 'Juice'], ['Banana', 'Fruit', 'Eat'], ['Mango', 'Fruit', 'Juice'], ['Mango', 'Fruit', 'Eat']]
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END