I have a 2D list called data
data = [['ABC', 12, 3, 100],
['DEF', 10, 5, 200],
['GHI', 13, 3, 1000]]
and 2 random numbers n1
and n2
(it is not limited with 2 numbers). Whenever I run my program n1 and n2 will be set between [0-3] randomly as data has 4 columns indexed between [0-3]. After that data should be sorted depending on the columns pointed by n1 and n2.
Let's say
n1
= 2
n2
= 3
Thus, the list should now be sorted by second column first and if the values in the second column are the same, sorting should be done depending on the third column and so on as you can see below
[['ABC', 12, 3, 100],
['GHI', 13, 3, 1000],
['DEF', 10, 5, 200]]
I am looking forward for your help. Thanks in advance
CodePudding user response:
from operator import itemgetter
data = [['ABC', 12, 3, 100],
['DEF', 10, 5, 200],
['GHI', 13, 3, 1000]]
indices = [2, 3]
res = sorted(data, key=itemgetter(*indices))
print(res)
Output
[['ABC', 12, 3, 100], ['GHI', 13, 3, 1000], ['DEF', 10, 5, 200]]
This will work for any number of indices.
CodePudding user response:
You can pass a tuple to the sort key:
sorted(data, key=lambda x: (x[n1],x[n2]))
CodePudding user response:
You might harness .sort
method of list which accept function as key
and does work in place i.e.
data = [['ABC', 12, 3, 100],
['DEF', 10, 5, 200],
['GHI', 13, 3, 1000]]
data.sort(key=lambda x:(x[2],x[3]))
print(data)
output
[['ABC', 12, 3, 100], ['GHI', 13, 3, 1000], ['DEF', 10, 5, 200]]
lambda
is used to create 2-tuple which are then used as values during sorting
CodePudding user response:
Use operator.itemgetter
for your sorting key function:
from operator import itemgetter
indices = [2, 3]
data.sort(key=itemgetter(*indices))
# [['ABC', 12, 3, 100],
# ['GHI', 13, 3, 1000],
# ['DEF', 10, 5, 200]]