How to sort 2d array by row in python?

前端 未结 5 1753
猫巷女王i
猫巷女王i 2020-12-03 07:41

I have 2d array, dimension 3x10, and I want to sort by values in 2nd row, from lowest to highest value.

5条回答
  •  暖寄归人
    2020-12-03 08:25

    Rather than use lambda x: x[1] you can use operator.itemgetter as the key to the sort or sorted functions. itemgetter(n) creates a function that gets the nth item from a list.

    >>> matrix = [ [4,5,6], [1,2,3], [7,0,9]]
    >>> from operator import itemgetter
    >>> sorted(matrix, key=itemgetter(1))
    [[7, 0, 9], [1, 2, 3], [4, 5, 6]]
    

提交回复
热议问题