Python| List 中每第 K 个元素删除
我们通常希望对列表中的所有元素使用特定的函数。但有时,根据要求,我们希望删除列表中的某些元素,基本上是列表中的每个第 K 个元素。让我们讨论可以执行此操作的某些方式。
方法 #1:使用列表理解 + enumerate()
获取每个第 K 个列表的功能可以在列表理解的帮助下完成,枚举函数有助于整个列表的迭代。
# Python3 code to demonstrate
# Every Kth element removal in List
# using list comprehension + enumerate()
# initializing list
test_list = [1, 4, 5, 6, 7, 8, 9, 12]
# printing the original list
print ("The original list is : " + str(test_list))
# initializing K
K = 3
# using list comprehension + enumerate()
# Every Kth element removal in List
# Remove every third element
res = [i for j, i in enumerate(test_list) if j % K != 0]
# printing result
print ("The list after removing every Kth element : " + str(res))
输出 :
The original list is : [1, 4, 5, 6, 7, 8, 9, 12]
The list after removing every kth element : [4, 5, 7, 8, 12]
方法#2:使用列表理解+列表切片
上述功能可以帮助执行这些任务。列表推导式完成列表中的迭代任务,列表切片完成每个 Kth 元素的提取。
# Python3 code to demonstrate
# Every Kth element removal in List
# using list comprehension + list slicing
# initializing list
test_list = [1, 4, 5, 6, 7, 8, 9, 12]
# printing the original list
print ("The original list is : " + str(test_list))
# initializing K
K = 3
# using list comprehension + list slicing
# Every Kth element removal in List
# removes every 3rd element
res = [i for i in test_list if i not in test_list[0 :: 3]]
# printing result
print ("The list after removing every Kth element : " + str(res))
输出 :
The original list is : [1, 4, 5, 6, 7, 8, 9, 12]
The list after removing every kth element : [4, 5, 7, 8, 12]