-1

I have an array which contains:

[['test3', ['7']], ['test4', ['1']], ['test', ['2', '4']], ['test1', ['2', '4']], ['test2', ['5']]]

I don't know how I can sort this by the length of the second item (= array) in the array of the full array. It should look like this when it is sorted:

[['test4', ['1']],  ['test2', ['5']], ['test3', ['7']], ['test', ['2', '4']], ['test1', ['2', '4']]]

It would be also nice if somebody knew how to sort it also by the numbers in the array.

The first item is not relevant.

martineau
  • 119,623
  • 25
  • 170
  • 301
FatJelly
  • 3
  • 2
  • Because it would be nice if the sorting would also sort it by the numbers in the array ['test3', ['7']] ( => so the 7 in there) – FatJelly Jan 06 '21 at 23:34
  • 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). “Show me how to solve this coding problem” is not a Stack Overflow issue. We expect you to make an honest attempt, and *then* ask a *specific* question about your algorithm or technique. Stack Overflow is not intended to replace existing documentation and tutorials. Sorting with a key is covered in any Python `sort` tutorial. Please compete your research before posting a question here. – Prune Jan 06 '21 at 23:36
  • Sorry but I could not find anything :( – FatJelly Jan 06 '21 at 23:38

1 Answers1

-1

You can use a key, so you could you the following code:

l = [['test3', ['7']], ['test4', ['1']], ['test', ['2', '4']], ['test1', ['2', '4']], ['test2', ['5']]]
l.sort(key=lambda item: (len(item[1]), str(item[1][0])))
abhigyanj
  • 2,355
  • 2
  • 9
  • 29