-1

I have python a list that looks like the following:

['T20221019A_E3.B Allele Freq',
 'T20221019A_E3.Log R Ratio',
 'T20221019A_E3.Gtype',
 'Father_FM.B Allele Freq',
 'Father_FM.Log R Ratio',
 'Father_FM.Gtype',
 'Mother_FS.B Allele Freq',
 'Mother_FS.Log R Ratio',
 'Mother_FS.Gtype']

First I would like to order this list based on what it is left of the dot '.' marker with the following order: Mother, Father and T20221019A_E3. This would be my first-level sort.

Then I would like to sort the string right of the dot '.' with the following order: Gtype, B Allele Freq and Log R Ratio

such that my re-ordered list look like so:

['Mother_FS.Gtype',
 'Mother_FS.B Allele Freq',
 'Mother_FS.Log R Ratio',
 'Father_FM.Gtype',
 'Father_FM.B Allele Freq',
 'Father_FM.Log R Ratio',
 'T20221019A_E3.Gtype',
 'T20221019A_E3.B Allele Freq',
 'T20221019A_E3.Log R Ratio',]

What would be the cleanest way of achieving this?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
BCArg
  • 2,094
  • 2
  • 19
  • 37
  • 1
    Does this answer your question? [Python sorting by multiple criteria](https://stackoverflow.com/questions/20145842/python-sorting-by-multiple-criteria) and [Sort a list with a custom order in Python](https://stackoverflow.com/q/14208256/6045800) – Tomerikoo Mar 13 '23 at 15:00

1 Answers1

0

Try:

def key_func(s):
    x, y = s.split(".", maxsplit=1)

    if x.startswith("Mother"):
        x = 1
    elif x.startswith("Father"):
        x = 2
    elif x.startswith("T20221019A_E3"):
        x = 3
    else:
        x = 4

    if y == "Gtype":
        y = 1
    elif y == "B Allele Freq":
        y = 2
    elif y == "Log R Ratio":
        y = 3
    else:
        y = 4

    return x, y


lst = [
    "T20221019A_E3.B Allele Freq",
    "T20221019A_E3.Log R Ratio",
    "T20221019A_E3.Gtype",
    "Father_FM.B Allele Freq",
    "Father_FM.Log R Ratio",
    "Father_FM.Gtype",
    "Mother_FS.B Allele Freq",
    "Mother_FS.Log R Ratio",
    "Mother_FS.Gtype",
]

lst.sort(key=key_func)
print(lst)

Prints:

[
    "Mother_FS.Gtype",
    "Mother_FS.B Allele Freq",
    "Mother_FS.Log R Ratio",
    "Father_FM.Gtype",
    "Father_FM.B Allele Freq",
    "Father_FM.Log R Ratio",
    "T20221019A_E3.Gtype",
    "T20221019A_E3.B Allele Freq",
    "T20221019A_E3.Log R Ratio",
]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91