how to sort numbers in an array ignoring text in Python?

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']] 


[[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

Submitted July 16th 2021 by Admin


You have a list of lists, not a multidimensional array. But this will do what you have asked

nums = [[4,'w'],[4,'a'],[2,'a']] foo = sorted(nums, key=lambda x: x[0])
print(foo) [[2, 'a'], [4, 'w'], [4, 'a']]

Admin | 1 week ago


Use operator.itemgetter

>>> from operator import itemgetter
>>> sorted(nums, key=itemgetter(0)) [[2, 'a'], [4, 'w'], [4, 'a']]

Admin | 1 week ago

Relevant Questions

Numpy advanced reshape?

September 22nd 2020