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
``
if column[3] < minimum:column here is already a row item so it wont be always subscriptable. you always want to look at the 4th item then you dont need the loopfor column in row[1:]:just the if. if all you want to do is sort then why not provide a custom key? also, its a big no no modifying your list while iterating over itlista.remove(minimum)is bad!