Python - 从列表中的第 K 个索引排序
给定一个元素列表,从 List 的第 K 个索引执行排序。
Input : test_list = [7, 3, 7, 6, 4, 9], K = 2
Output : [7, 3, 4, 6, 7, 9]
Explanation : List is unsorted till 3 (1st index), From 2nd Index, its sorted.
Input : test_list = [5, 4, 3, 2, 1], K= 3
Output : [5, 4, 3, 1, 2]
Explanation : Only last two elements, 1, 2 are sorted.
方法#1:使用循环+列表切片
这是可以执行此任务的方式之一。在此,我们提取列表中 K 之前的每个元素,然后使用切片符号执行列表切片,并对提取的切片列表执行排序。
Python3
# Python3 code to demonstrate working of
# Perform sort from Kth index
# Using loop + list slicing
# initializing list
test_list = [8, 4, 7, 3, 2, 14, 6]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 3
# Using loop + list slicing
res = []
# Using loop to extract elements till K
for idx, ele in enumerate(test_list):
if idx < K:
res.append(ele)
# join sorted and unsorted segments
res = res + sorted(test_list[K:])
# printing result
print("Partially sorted list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Perform sort from Kth index
# Using Using double List slicing
# initializing list
test_list = [8, 4, 7, 3, 2, 14, 6]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 3
# Using loop + list slicing
res = []
# Using loop to extract elements till K
# Concatenating unsort and sorted part as one liner
res = test_list[:K] + sorted(test_list[K:])
# printing result
print("Partially sorted list : " + str(res))
输出
The original list : [8, 4, 7, 3, 2, 14, 6]
Partially sorted list : [8, 4, 7, 2, 3, 6, 14]
方法#2:使用双列表切片
这是我们执行此任务的另一种方式。在此,我们执行列表切片任务以切片未排序部分并执行连接,提供一个单行替代方案来解决此问题。
Python3
# Python3 code to demonstrate working of
# Perform sort from Kth index
# Using Using double List slicing
# initializing list
test_list = [8, 4, 7, 3, 2, 14, 6]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 3
# Using loop + list slicing
res = []
# Using loop to extract elements till K
# Concatenating unsort and sorted part as one liner
res = test_list[:K] + sorted(test_list[K:])
# printing result
print("Partially sorted list : " + str(res))
输出
The original list : [8, 4, 7, 3, 2, 14, 6]
Partially sorted list : [8, 4, 7, 2, 3, 6, 14]