📜  Python – 最近的 K 排序

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

Python – 最近的 K 排序

给定一个元素列表,根据它与 K 的距离进行排序。

方法 #1:使用 sort() + abs()

在这里,我们使用sort()进行排序, abs()用于获取差异,用于逻辑形成以对其进行排序操作。

Python3
# Python3 code to demonstrate working of
# Nearest K Sort
# Using sort() + abs()
  
# getting absolute difference
def get_diff(ele):
  
    # returning absolute difference
    return abs(ele - K)
  
  
# initializing list
test_list = [6, 7, 4, 11, 17, 8, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 10
  
# performing inplace sort using sort()
test_list.sort(key=get_diff)
  
# printing result
print("Sorted List : " + str(test_list))


Python3
# Python3 code to demonstrate working of
# Nearest K Sort
# Using sorted() + abs() + lambda
  
# initializing list
test_list = [6, 7, 4, 11, 17, 8, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 10
  
# sorted() used to perform sorting, lambda function to get logic
res = sorted(test_list, key=lambda ele: abs(ele - K))
  
# printing result
print("Sorted List : " + str(res))


输出
The original list is : [6, 7, 4, 11, 17, 8, 3]
Sorted List : [11, 8, 7, 6, 4, 17, 3]

方法#2:使用 sorted() + lambda + abs()

与上述方法类似,这里使用sorted()来执行排序操作,而不是调用外部函数,而是使用lambda来提供排序逻辑。

蟒蛇3

# Python3 code to demonstrate working of
# Nearest K Sort
# Using sorted() + abs() + lambda
  
# initializing list
test_list = [6, 7, 4, 11, 17, 8, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 10
  
# sorted() used to perform sorting, lambda function to get logic
res = sorted(test_list, key=lambda ele: abs(ele - K))
  
# printing result
print("Sorted List : " + str(res))
输出
The original list is : [6, 7, 4, 11, 17, 8, 3]
Sorted List : [11, 8, 7, 6, 4, 17, 3]