How to sort 2d array by row in python?

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

    This is a little function I wrote for this purpose:

    def sorted_table(data, column=0, reverse=False):
        return sorted(data, cmp=lambda a,b: cmp(a[column], b[column]), reverse=reverse)
    

    Actually, I had a bit more complex requirement, which is to sort the table by two columns. It turns out that the cmp() function is quite versatile; this is my original function:

    def sort_report(data):
        """Sort report columns: first by value, then by label."""
        return sorted(data, cmp=lambda a,b: cmp(b[2], a[2]) or cmp(a[0], b[0])) # label is column 0; value is column 2
    

    The b and a are reversed in the first case, since the goal was to sort the values fro higher to lower.

提交回复
热议问题