I would like to sort a 2D list, but by using the last column as the sorter. Here is the list:
list_2 = [['countries', 2019, 2020, 2025],['aruba', 2,2,9],['barbados', 2,2,3],['japan', 2,2,5]]
The first row with countries and years, must not be sorted. The second third and fourth row with countries and data needs be sorted by the last column. Here is my function so far:
#create a new analyzed and sorted list, empty, to be used in further analysis
listAnalyzedSort = []
def sortData(lista):
#this function sorts data in the inputed list
#inputed argument is a list
#output is a sorted list by the last column
while lista:
minimum = lista[1][3]
for row in lista:
for column in row[1:]:
if column[3] < minimum:
minimum = column
listAnalyzedSort.append(minimum)
lista.remove(minimum)
return listAnalyzedSort
sortData(list_2)
It gives me an error
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
C:\Users\JONATH~1.COL\AppData\Local\Temp/ipykernel_10168/956311210.py in <module>
18 return listAnalyzedSort
19
---> 20 sortData(list_2)
C:\Users\JONATH~1.COL\AppData\Local\Temp/ipykernel_10168/956311210.py in sortData(lista)
12 for row in lista:
13 for column in row[1:]:
---> 14 if column[3] < minimum:
15 minimum = column
16 listAnalyzedSort.append(minimum)
TypeError: 'int' object is not subscriptable
``
CodePudding user response:
Just exclude the first entry and then sort the remaining, later just append the first country to the result
lista = [['countries', 2019, 2020, 2025],['aruba', 2,2,1],['barbados', 2,2,2],['japan', 2,2,3]]
sortedout = sorted(lista[1:],key=lambda x:x[-1], reverse=True)
out = [lista[0]] sortedout
print(out)
output will be
[['countries', 2019, 2020, 2025], ['japan', 2, 2, 3], ['barbados', 2, 2, 2], ['aruba', 2, 2, 1]]
CodePudding user response:
Only sort the list starting at the element at index 1 and use a key function that retrieves the last element of the inner list. Then add this new sorted list to the element at index 0.
lista = [['countries', 2019, 2020, 2025],['japan', 2,2,3],['barbados', 2,2,2],['aruba', 2,2,1]]
result = lista[0] sorted(lista[1:], key=lambda x: x[-1])
print(result)
This will give you ['countries', 2019, 2020, 2025, ['aruba', 2, 2, 1], ['barbados', 2, 2, 2], ['japan', 2, 2, 3]]
CodePudding user response:
Here you will find a solution that is similar to your approach.
def sortData(lista):
listAnalyzedSort = lista[:2]
del lista[:2]
for row in lista:
max = 1
for idx, ele in enumerate(listAnalyzedSort[1:]):
if row[3] < ele[3]:
max = idx 1
listAnalyzedSort.insert(max, row)
return listAnalyzedSort
Note that it tries to follow your logic by comparing the third element of a given row to the third element of every row of the resulting list, and then inserting the given row at the appropriate position.
It returns: [['countries', 2019, 2020, 2025], ['barbados', 2, 2, 3], ['japan', 2, 2, 5], ['aruba', 2, 2, 9]]