0

I have a list of ['rs12345','rs21','rs55189']; I need to sort them as numbers after strip the prefix 'rs'.

How can I do it in Python ?

# row.keys() is ['rs12345','rs21','rs55189']
fieldnames = sorted(list(row.keys()),key=itemgetter(slice(2, None)))

This code will not working after add int(''.join(xxx)).

And the dict row is a generator so I have to put it into list() to get its values.


_fieldnames = list(row.keys())
_fieldnames.remove(sidname)
_fieldnames = sorted(_fieldnames, key=lambda i: int(i[2:]))

Got it working. I forgot that I have to remove sampleid, which contains no ^rs, first.

martineau
  • 119,623
  • 25
  • 170
  • 301
Galaxy
  • 1,862
  • 1
  • 17
  • 25
  • 1
    `key=lambda i: int(i[2:])` – deceze Jun 22 '21 at 08:44
  • Is there and thing like "$_" in Perl to be put into `i` ? – Galaxy Jun 22 '21 at 08:47
  • Is this a question about Perl, or Python? – quamrana Jun 22 '21 at 08:48
  • 2
    Note that you might also simply consider a [natsort](https://stackoverflow.com/q/4836710/476). – deceze Jun 22 '21 at 08:48
  • The suggested duplicate question has accepted answer: *"use `.split('_')[1]` to separate the prefix from the number"*. But that doesn't apply here, since there is no `'_'` character in the strings... – Stef Jun 22 '21 at 08:48
  • @Stef No, it's not an *exact* solution, but it illustrates the correct approach (which `itemgetter(slice ...)` is simply not). We do expect a *bit* of work to be done to adjust to the situation as necessary. And nevertheless, I posted the exact solution as the first comment. – deceze Jun 22 '21 at 08:50
  • @deceze Yes, I find your code is ready to work. I forgot to exclude the first element before sort. – Galaxy Jun 22 '21 at 08:53

0 Answers0