0

soo I have a problem. I would like to sort a list, with an other list inside (which contains numbers and text) by numbers but if there are 2 same numbers then sort should not sort by text, in other words, let the sort skip text.

My code:

nums = [[4,'w'],[4,'a'],[2,'a']] 
print(sorted(nums))

Result:

[[2, 'a'], [4, 'a'], [4, 'w']]

What I want to have:

[[2, 'a'], [4, 'w'], [4, 'a']]

As you can see, in "what I want to have" the [4,'w'] and [4,'a'] have not changed places, but they have changed places during sorting

Please help me recieve "what I want to have"

And sorry for my bad English, I'm not an English native speaker

1 Answers1

3

You have a list of lists, not a multidimensional array. But this will do what you have asked.
x[0] will sort by first index of each list.

nums = [[4,'w'],[4,'a'],[2,'a']]

foo = sorted(nums, key=lambda x: x[0])
print(foo)

[[2, 'a'], [4, 'w'], [4, 'a']]
SimonT
  • 974
  • 1
  • 5
  • 9
  • yeah it kinda works, but what if I want to sort this: ```nums = [[4,6,'t'],[4,10,'c'],[2,3,'a']]``` it gives me this result: ```[[2, 3, 'a'], [4, 6, 't'], [4, 10, 'c']]``` and 10 is bigger than 6 so why 6 is on right and ten on left? –  Jul 16 '21 at 20:00
  • Because you are only sorting the first index of each list, which is what the [0] does. This is a totally different question you are asking now. I don't understand what you mean? 10 is not on the left of anything? You can add multiple lambdas ```foo = sorted(nums, key=lambda x: (x[0], x[1]))``` Or you can use ```operator.itemgetter``` as @Corralien suggested – SimonT Jul 16 '21 at 20:17