Pythonでは、リストの特定のインデックスに基づいてリストをソートすることが可能です。以下にその方法を2つ紹介します。
泡立てソートアルゴリズムを使用する方法
泡立てソートは、リストを通過し、隣接する各ペアを比較し、順序が間違っていれば交換するというシンプルなソートアルゴリズムです。リストがソートされていることを示す交換が必要ないまで、リストを通過することを繰り返します。
test_list = [ ['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]]
print("The original list is : " + str(test_list))
n = len(test_list)
for i in range(n):
for j in range(n-1):
if test_list[j][1] > test_list[j+1][1]:
test_list[j], test_list[j+1] = test_list[j+1], test_list[j]
print("List after sorting by 2nd element of lists : " + str(test_list))
sort() + lambdaを使用する方法
Pythonのsort()関数を使用して、リストをソートすることも可能です。この方法では、キーとしてlambda関数を使用して、各リストの2番目の要素を返します。
test_list = [ ['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]]
print("The original list is : " + str(test_list))
test_list.sort(key=lambda test_list: test_list[1])
print("List after sorting by 2nd element of lists : " + str(test_list))
これらの方法を使用すると、Pythonでリストの特定のインデックスに基づいてリストをソートすることが可能になります。