sakirecayyok
sakirecayyok

Reputation: 29

Sorting a list key parameter

I have a problem on sorting a list, my goal is I'm trying to write a function that will sort a list of files based on their extension. For example given;

["a.c","a.py","b.py","bar.txt","foo.txt","x.c"]

desired output is;

["a.c","x.c","a.py","b.py","bar.txt","foo.txt"]

I fail when I tried to make a key parameter, I can't creating the algorithm. I tried to split() every file first, like;

def sort_file(lst):
    second_list = []
    for x in lst:
        t = x.split(".")
        second_list.append(t[1])
    second_list.sort()

But I just don't know what to do now, how can I make this sorted second_list as a key parameter then I can sort files based on their extension?

Upvotes: 2

Views: 161

Answers (1)

UltraInstinct
UltraInstinct

Reputation: 44444

I fail when I tried to make a key parameter

key argument takes a function (callable, rather), that returns the object to compare against when given the list item as input. In your case, the x.split(".")[1] is the object to compare against. Take a look at Python's wiki entry for sorting in this fashion

Something like the below should work for you.

>>> a = ["a.c","a.py","b.py","bar.txt","foo.txt","x.c"]
>>> sorted(a, key=lambda x: x.rsplit(".", 1)[1])
['a.c', 'x.c', 'a.py', 'b.py', 'bar.txt', 'foo.txt']

As @TanveerAlam says, using rsplit(..) is better because you'd want the split to be done from right.

Upvotes: 2

Related Questions