📜  Python列表 |流行音乐()

📅  最后修改于: 2022-05-13 01:55:10.600000             🧑  作者: Mango

Python列表 |流行音乐()

Python list pop()是Python中的一个内置函数,它从 List 或给定的索引值中删除并返回最后一个值。

示例 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, "\n")
 
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, "\n")


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)


Python3
# Python3 program for error in pop() method
 
list1 = [ 1, 2, 3, 4, 5, 6 ]
print(list1.pop(8))


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)


输出:

6
New List after pop :  [1, 2, 3, 4, 5] 

4
('cat', 'bat')
3
New 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:实际示例

水果列表包含fruit_name和表示其水果的属性。另一个清单消费有两个项目果汁。在 pop() 和 append() 的帮助下,我们可以做一些有趣的事情。

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']]