-2

I have a list A containing many sublists. I want to reorganize this list based on the first element of each sublist i.e. in ascending order. I present the current and expected output.

A=[[27, 31, 32, 36], [30, 34, 35, 39], [28, 32, 33, 37], [29, 33, 34, 38]]
C=[]


for i in range(0,len(A)):
    B=A[i][0]
    C.append(B)
    C.sort()
    print(C)

The current output is

[27, 28, 29, 30]

The expected output is

[[27, 31, 32, 36], [28, 32, 33, 37], , [29, 33, 34, 38], [30, 34, 35, 39]]
  • 1
    `C = sorted(A)`? – Mark Feb 24 '23 at 05:37
  • try `A.sort(key=lambda x: x[0])` – Yash Mehta Feb 24 '23 at 05:37
  • It's not though. The output is `[27]`, followed by `[27, 30]`, etc. And that makes sense because you are adding `A[i][0]` to `B`. And `A[i]` is the i-th list in A (like `[27, 31, 32, 36]` for `i == 0`) and with `[0]` you are adding only the first element. – Grismar Feb 24 '23 at 05:38
  • Does this answer your question? [Sorting list of lists by the first element of each sub-list](https://stackoverflow.com/questions/36955553/sorting-list-of-lists-by-the-first-element-of-each-sub-list) – Yash Mehta Feb 24 '23 at 05:43

2 Answers2

2

You can use the key argument to the sorted function, and the lambda keyword to create an anonymous function which returns the first element of a list.

>>> A=[[27, 31, 32, 36], [30, 34, 35, 39], [28, 32, 33, 37], [29, 33, 34, 38]]
>>> sorted(A, key = lambda iterable: iterable[0])
    [[27, 31, 32, 36], [28, 32, 33, 37], [29, 33, 34, 38], [30, 34, 35, 39]]

For sorting by the first element only, sorted does this by default, and so just sorted(A) will do the trick. The method presented above works for all indices.

Mous
  • 953
  • 3
  • 14
1

So you just need to use sorted coupled with a lambda function as the key:

C = sorted(A, key=lambda x: x[0], reverse=False)
NotAName
  • 3,821
  • 2
  • 29
  • 44