Home > Mobile >  Is there a way to make extentions ordered alphabetically, not based on length?
Is there a way to make extentions ordered alphabetically, not based on length?

Time:07-10

I've been using this code to order the extention based on alphabetical order

def sort_by_ext(files: List[str]) -> List[str]:
    sort1 = sorted(files, key=lambda x: x[x.rindex("."):-1])
    return sort1

When this code uses the input (["x.bit","y.man","format.c"]), format.c is first when I wanted it in position 1. Is there a way to do so?

CodePudding user response:

Here:

sort1 = sorted(files, key=lambda x: x[x.rindex("."):-1])

the :-1 in the slice cuts off the last character. With a .c extension you lose the c. Use None or leave the position empty.

Demo:

inp = ["x.bit","y.man","format.c"]
print([x[x.rindex("."):-1] for x in inp])
#                      ^^

prints: ['.bi', '.ma', '.']

  • Related