-1

I'm trying to sort these coordinates by the first element and the second element. The first element are just simple alphabets, and the second element are numerical values.

I found out how to make the program print by the first element - by alphabetical order. Which works - but I'm having difficulties with attempting to solve it by the numerical values.

How would this problem be apporached?

coor_tuples = [
                ('f', 9),
                ('z,', 2),
                ('t', 4),
                ('x', 8),
                ('b', 1),
                ('m', 7)
]

sorted(coor_tuples, key=lambda coor: coor[1])

print(coor_tuples)
Crunchdomo
  • 1
  • 1
  • 1
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). In particular, we need you to specify what you're trying to do; include an example or two. Give us the expected [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example), so we can see exactly where you need help. – Prune Sep 25 '20 at 04:02
  • `sorted` doesn't work in place, you need to assign the output... – Nick Sep 25 '20 at 04:03
  • Also, make sure that you have consulted applicable tutorials on sorting. – Prune Sep 25 '20 at 04:03
  • Does this answer your question? [What is the difference between \`sorted(list)\` vs \`list.sort()\`?](https://stackoverflow.com/questions/22442378/what-is-the-difference-between-sortedlist-vs-list-sort) – Nick Sep 25 '20 at 04:04

3 Answers3

0

The problem is that the sorted function returns the sorted array, leaving the original array intact, instead of sorting the array you put in. You should try

coor_tuples = [
                ('f', 9),
                ('z,', 2),
                ('t', 4),
                ('x', 8),
                ('b', 1),
                ('m', 7)
]

coor_tuples=sorted(coor_tuples, key=lambda coor: coor[1])

print(coor_tuples)
aidan0626
  • 307
  • 3
  • 8
0

The sorted method returns a sorted collection. You need to set it.

coor_tuples = [
                ('f', 9),
                ('z,', 2),
                ('t', 4),
                ('x', 8),
                ('b', 1),
                ('m', 7)
]

coor_tuples = sorted(coor_tuples, key=lambda coor: coor[1])  # update collection

print(coor_tuples)

Output

[('b', 1), ('z,', 2), ('t', 4), ('m', 7), ('x', 8), ('f', 9)]
Mike67
  • 11,175
  • 2
  • 7
  • 15
0

You forgot to assign back to coor_tuples, so the result of sorted is discarded. Either assign back:

coor_tuples = sorted(coor_tuples, key=lambda coor: coor[1])

or use the .sort method instead, to sort in place:

coor_tuples.sort(key=lambda coor: coor[1])

I'd recommend the latter in this case, since it's already a list; unless you need the original unsorted data, there's no reason not to sort in place and save unnecessary temporaries.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271