Python|截断列表
有时需要将列表大小限制为特定数字,并从列表中删除在确定为列表大小的某个数字之后出现的所有元素。这是使用Python进行 Web 开发的有用实用程序。让我们讨论可以执行此操作的某些方式。
方法 #1:使用pop()
pop
函数可以重复多次,直到列表大小达到列表大小所需的阈值。这使用了一个完整的循环,因此比较乏味。
# Python3 code to demonstrate
# to truncate list using pop()
# initializing list
test_list = [1, 4, 5, 6, 7, 3, 8, 9, 10]
# printing original list
print ("The original list is : " + str(test_list))
# size desired
k = 5
# using pop()
# to truncate list
n = len(test_list)
for i in range(0, n - k ):
test_list.pop()
# printing result
print ("The truncated list is : " + str(test_list))
输出:
The original list is : [1, 4, 5, 6, 7, 3, 8, 9, 10]
The truncated list is : [1, 4, 5, 6, 7]
方法 #2:使用 del + list slice
del
运算符可用于删除出现在特定索引之后的所有元素,这由列表切片技术处理。
# Python3 code to demonstrate
# to truncate list
# using del + list slicing
# initializing list
test_list = [1, 4, 5, 6, 7, 3, 8, 9, 10]
# printing original list
print ("The original list is : " + str(test_list))
# size desired
k = 5
# using del + list slicing
# to truncate list
del test_list[5:]
# printing result
print ("The truncated list is : " + str(test_list))
输出:
The original list is : [1, 4, 5, 6, 7, 3, 8, 9, 10]
The truncated list is : [1, 4, 5, 6, 7]
方法#3:使用列表切片
在这种方法中,我们只对前 K 个元素进行切片,而忽略K个元素之后出现的所有元素。这是执行此任务的最 Pythonic 和推荐的方法。
# Python3 code to demonstrate
# to truncate list
# using list slicing
# initializing list
test_list = [1, 4, 5, 6, 7, 3, 8, 9, 10]
# printing original list
print ("The original list is : " + str(test_list))
# size desired
k = 5
# using list slicing
# to truncate list
res = test_list[0 : 5]
# printing result
print ("The truncated list is : " + str(res))
输出:
The original list is : [1, 4, 5, 6, 7, 3, 8, 9, 10]
The truncated list is : [1, 4, 5, 6, 7]