Python程序删除列表中小于K差的元素
给定一个列表,删除与其前一个元素差异小于 K 的那些元素。
Input : test_list = [3, 19, 5, 8, 10, 13], K = 4
Output : [3, 8, 13, 19]
Explanation : 5 – 3 = 2, 2<4, hence 5 is removed, similarly, 10 – 8 is 2, less than K.
Input : test_list = [15, 7, 20], K = 4
Output : [7, 15, 20]
Explanation : No deletion required.
方法: 使用循环和 sorted()
在这种情况下,首先必须对列表进行排序,然后删除在其前后元素之间没有适当距离的元素。
Python3
# initializing list
test_list = [3, 19, 4, 8, 10, 13]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# sorting list
test_list = sorted(test_list)
idx = 0
while idx < len(test_list) - 1:
# checking for difference
if test_list[idx] + K > test_list[idx + 1]:
# deleting if K closer
del test_list[idx + 1]
else:
idx += 1
# printing result
print("Required List : " + str(test_list))
输出:
The original list is : [3, 19, 4, 8, 10, 13]
Required List : [3, 8, 13, 19]