1

I have a list of tuples as such:

listTup = [('5.1','@1fedb3d2',1), ('5.10','@79109bbe',1), ('5.3','@b52bd219',1), ('5.2','@e4e9b43e',1), ('5.11','@2538bf70',1)]

and would like to sort it using the first element in each tuple (where the first element is a version number) so that the end result is:

listTup = [('5.1','@1fedb3d2',1), ('5.2','@e4e9b43e',1), ('5.3','@b52bd219',1), ('5.10','@79109bbe',1),('5.11','@2538bf70',1)]

I am able to sort a list in increasing version number with

list.sort(key=lambda s: map(int, s.split('.')))

but when used with a list of tuples in the following way:

listTup = *sorted(listTup,key=lambda s: map(int, s.split('.')))

yields the error

'tuple' object has no attribute 'split'

I believe it is simply a matter of making the code directly find the first element of each tuple by combining the previous line of code with

listTup.sort(key=lambda x: x[0])

but I have not been able to find how to do so. I must also note that I am unable to use libraries like numpy as the software I am writing in is unable to import libraries and packages.

nahey
  • 11
  • 1
  • `listTup.sort(key=lambda s: list(map(int, s[0].split('.'))))` - beside that - dont call things `list` - you hide the built in. – Patrick Artner Jul 05 '20 at 12:17
  • Wow the fix was so much more straightforward than expected, thanks a lot @PatrickArtner – nahey Jul 05 '20 at 12:26

1 Answers1

-1

The correct way to do it is:

listTup.sort(key=lambda x: int(x[0].split('.')[1]))

The key=lambda function receives a tuple from your list which cannot be split. Instead you need the first element x[0] of the tuple. After split (which returns a list), you need the second element ()[1] which is the key you want.

Ronald
  • 2,930
  • 2
  • 7
  • 18