Click here to Skip to main content
15,903,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can I sort by an element in a list of numbers? For example, sort by element 2:
```
 {[0, 13, 24], [0, 6, 8], [37, 2, 100]}
```
Expected result:
```
{[0, 6, 8], [0, 13, 24], [37, 2, 100]}
```
I tried using `key = lambda x:x[2]` but it did not work, gave an error of ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

I researched about using `key`. The closest I could get to a solution was `x=x[2]` but
it would not work and would give the error that when fixed would not function as intended.
I even tried using item getter but it would fail and say "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()" I researched this error but it didn't make sense why this would be popping up.

`rend = [[0, 0, 0], [100, 0, 0], [0, 100, 0], [100, 0, 0], [100, 100, 0], [0, 100, 0], [0, 0, 100], [100, 0, 100], [0, 100, 100], [100, 0, 100], [100, 100, 100], [0, 100, 100], [0, 0, 0], [0, 100, 0], [0, 100, 100], [0, 0, 100], [0, 100, 100], [0, 0, 0], [100, 0, 0], [100, 100, 0], [100, 100, 100], [100, 0, 100], [100, 100, 100], [100, 0, 0], [0, 0, 0], [100, 0, 0], [100, 0, 100], [0, 0, 0], [0, 0, 100], [100, 0, 100], [0, 100, 0], [100, 100, 0], [100, 100, 100], [0, 100, 0], [0, 100, 100], [100, 100, 100]]
`
```
a = 0
tosort = []
    for I in range(round(len(rend)/3)):
        tosort.append((rend[a], rend[a+1], rend[a+2]))
        a += 3
    EDI = sorted(tosort, key = itemgetter(2))
```


What I have tried:

I have tried x[2], itemgetter(2), and some other lambda functions
Posted
Updated 2-Nov-22 21:45pm

1 solution

Note, the index of the second item of a list is 1 (instead of 2).
Try
Python
l = [[0, 13, 24], [0, 6, 8], [37, 2, 100]]

l.sort(key = lambda item: item[1])

print(l)
 
Share this answer
 
Comments
Patrice T 3-Nov-22 4:40am    
+5
CPallini 3-Nov-22 8:33am    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900