在本文中,我们将学习如何根据主列表中存在的子列表的第二个元素对任何列表进行排序。
比如
Input : [[‘rishav’, 10], [‘akash’, 5], [‘ram’, 20], [‘gaurav’, 15]]
Output : [[‘akash’, 5], [‘rishav’, 10], [‘gaurav’, 15], [‘ram’, 20]]Input : [[‘452’, 10], [‘256’, 5], [‘100’, 20], [‘135’, 15]]
Output : [[‘256’, 5], [‘452’, 10], [‘135’, 15], [‘100’, 20]]
方法1:使用冒泡排序
这里我们使用了冒泡排序来执行排序。尝试使用嵌套循环访问子列表的第二个元素,这将执行就地排序方法。时间复杂度类似于冒泡排序,即,时间复杂度为O(n^2)。
def Sort(sub_li):
l = len(sub_li)
for i in range(0, l):
for j in range(0, l-i-1):
if (sub_li[j][1] > sub_li[j + 1][1]):
tempo = sub_li[j]
sub_li[j] = sub_li[j + 1]
sub_li[j + 1] = tempo
return sub_li
# Input list
sub_li = [['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
# Printing the list
print(Sort(sub_li))
输出
[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]
方法2:使用sort()方法
当通过该方法排序时,元组的实际内容被改变,并且就像前面的方法一样,执行就地排序。
def Sort(sub_li):
# reverse = None (Sorts in Ascending order)
# key is set to sort using second element of
# sublist lambda has been used
sub_li.sort(key = lambda x: x[1])
return sub_li
# Input list
sub_li =[['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
# Printing the sub list
print(Sort(sub_li))
输出
[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]
时间复杂度:O(n*logn)
方法3:使用sorted()方法进行
sorted()对列表进行排序,并始终返回一个包含元素的列表,而不修改原始序列。
def Sort(sub_li):
# reverse = None (Sorts in Ascending order)
# key is set to sort using second element of
# sublist lambda has been used
return (sorted(sub_li, key=lambda x: x[1]))
# Input list
sub_li = [['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
# Printing resultant list
print(Sort(sub_li))
输出
[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]
方法4: 使用OrderedDict
from collections import OrderedDict
def Sort(sub_li):
# create an ordered dictionary
sub_li_dict = OrderedDict()
for i in sub_li:
sub_li_dict[i[1]] = i
# sorting the dictionary by key
sorted_dict = sorted(sub_li_dict.items())
# extracting the values from the sorted dictionary
sort_sub_li = [value for key, value in sorted_dict]
return sort_sub_li
# Driver Code
sub_li =[['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
print(Sort(sub_li))
输出
[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]
上述方法实现了将子列表元素存储为键值对的有序字典。然后,字典按键排序,并返回列表,其中元素根据子列表中的第二个元素排序。
方法5: 使用operator模块中的itemgetter()
from operator import itemgetter
def sort_tuples(sub_li):
# itemgetter(1) returns a function that can be used to retrieve the
# second element of a tuple (i.e., the element at index 1)
# this function is used as the key for sorting the sublists
return sorted(sub_li, key=itemgetter(1))
# Input list
sub_li = [['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
# Printing resultant list
print(sort_tuples(sub_li))
输出
[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]
方法6: 使用numpy的argsort()
import numpy as np
# Define the input list
sub_li = [['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
# Converting the list to a NumPy array
sub_arr = np.array(sub_li)
# Extracting the second column and convert it to integers
values = sub_arr[:, 1].astype(int)
# Sort the array by the second column (index 1)
sorted_arr = sub_arr[values.argsort()]
# Converting the sorted array back to a list
sorted_li = sorted_arr.tolist()
# Printing sorted list
print(sorted_li)
输出
[['akash', '5'], ['rishav', '10'], ['gaurav', '15'], ['ram', '20']]
方法7: 使用递归
- 定义一个
merge()
函数,它接收两个列表(left
和right
),并将它们合并,同时根据子列表的第二个元素进行排序。 - 在
merge()
函数中,初始化一个空列表result
来存储合并后的和排序后的子列表。 - 将两个指针
i
和j
初始化为0,分别表示left
和right
中的当前索引。 - 比较子列表中
left[i]
和right[j]
的第二个元素。 - 如果
left[i]
的第二个元素小于或等于right[j]
的第二个元素,则将left[i]
追加到result
并递增i
。 - 否则,将
right[j]
追加到result
并递增j
。 - 重复步骤4-6,直到
left
或right
用尽为止。 - 将
left
和right
中的剩余元素附加到result
(如果有的话)。 - 返回
result
作为合并和排序的列表。
def merge(left, right):
# Empty list to store merge and sorted list
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i][1] <= right[j][1]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
# Recursive function to sort sub list
def sort_recursive(sub_li):
if len(sub_li) <= 1:
return sub_li
mid = len(sub_li) // 2
left = sub_li[:mid]
right = sub_li[mid:]
left = sort_recursive(left)
right = sort_recursive(right)
return merge(left, right)
# Input sub list
sub_li = [['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
# Calling function and printing sub list
print(sort_recursive(sub_li))
输出
[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]
这个算法的时间复杂度是O(n log n),其中n是输入列表sub_li
的长度。这是因为列表被递归地分成两半,直到达到单个元素或空列表的基本情况,然后在排序时合并回递归树,取log n级。在每个级别上,合并操作需要时间O(n)。