How to sort 2d array by row in python?

前端 未结 5 1760
猫巷女王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:22

    Well, if you're talking about standard python lists, this is easy: mylist[1].sort(). For example:

    >>> from random import randint
    >>> a_list = [[randint(1,15) for _ in range(10)] for _ in range(3)]
    >>> print a_list
    [[3, 12, 3, 12, 13, 5, 12, 2, 1, 13], [3, 8, 7, 4, 6, 11, 15, 12, 4, 6], [15, 3, 8, 15, 1, 6, 4, 7, 15, 14]]
    >>> a_list[1].sort()
    >>> print a_list
    [[3, 12, 3, 12, 13, 5, 12, 2, 1, 13], [3, 4, 4, 6, 6, 7, 8, 11, 12, 15], [15, 3, 8, 15, 1, 6, 4, 7, 15, 14]]
    

提交回复
热议问题