3

I have a an element k and list of lists which I named as A . I have to sort elements in A using sorted function based on k'th element in A .

Ex :

k=1  
A=[[10,20,30],[100,5,300]]

Output should be

[[100,5,300],[10,20,30]] 

I can do this easily using below code .

def mysort(x):
    return (x[k])
 k=1
 A=[[10,20,30],[100,5,300]]
 print(sorted(A,key=mysort))

But what I am asking here is I want to pass the variable k in to function mysort .

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69

4 Answers4

2

operator.itemgetter is convenient for your specific use case:

from operator import itemgetter

res = sorted(A, key=itemgetter(k))

functools.partial offers a more general solution:

from functools import partial

def mysort(x, index):
    return x[index]

res = sorted(A, key=partial(mysort, index=k))
jpp
  • 159,742
  • 34
  • 281
  • 339
0

You can create a lambda for that - lambdas are (kindof) anonymous functions:

k=1
A=[[10,20,30],[100,5,300]]
print(sorted(A,key=lambda x:x[k]))

Output:

[[100, 5, 300], [10, 20, 30]]

This post why-are-python-lambdas-useful explains it in some more detail and the official documentation is here: lambda expressions
The lambda lambda x:x[k] uses every element of A and from it the k-th value to sort your list.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

I think what you're looking for is this:

def mysort(k):
    return lambda x: x[k]
# ...
sorted(A, key=mysort(k))

Fortunately for you, this is alrealy implemented in operator from the standard library:

from operator import itemgetter
k = 1
sorted(A, key=itemgetter(k))
roeen30
  • 759
  • 3
  • 13
0

You can build the function for the key paramerer dynamically using closures:

def mysort(k):
  def f(x):
    return x[k]
  return f

k=1
A=[[10,20,30],[100,5,300]]
print(sorted(A,key=mysort(k)))