Python|记录的后方添加
有时,在使用Python列表时,我们可能会遇到需要向现有列表添加新元组的问题。在后面追加通常比在前面添加更容易。让我们讨论可以执行此任务的某些方式。
方法 #1:使用insert()
这是可以将元素添加到单衬里的方式之一。它用于在列表后面添加任何元素。元组的行为也是相同的。
# Python3 code to demonstrate working of
# Rear Addition of Record
# using insert()
# Initializing list
test_list = [('is', 2), ('best', 3)]
# printing original list
print("The original list is : " + str(test_list))
# Initializing tuple to add
add_tuple = ('gfg', 1)
# Rear Addition of Record
# using insert()
test_list.insert(len(test_list), add_tuple)
# printing result
print("The tuple after adding is : " + str(test_list))
输出 :
The original list is : [('is', 2), ('best', 3)]
The tuple after adding is : [('is', 2), ('best', 3), ('gfg', 1)]
方法 #2:使用deque() + append()
上述功能的组合可用于执行此特定任务。在这种情况下,我们只需要将列表转换为双端队列,以便我们可以使用 append() 在右侧执行追加。
# Python3 code to demonstrate working of
# Rear Addition of Record
# using deque() + append()
from collections import deque
# Initializing list
test_list = [('is', 2), ('best', 3)]
# printing original list
print("The original list is : " + str(test_list))
# Initializing tuple to add
add_tuple = ('gfg', 1)
# Rear Addition of Record
# using deque() + append()
res = deque(test_list)
res.append(add_tuple)
# printing result
print("The tuple after adding is : " + str(list(res)))
输出 :
The original list is : [('is', 2), ('best', 3)]
The tuple after adding is : [('is', 2), ('best', 3), ('gfg', 1)]