sorting list python

Peter Otten __peter__ at web.de
Wed Jan 18 15:20:17 EST 2017


Smith wrote:

> Hi all,
> could you do better?
> Thank you in advance
> 
> link code:
> https://repl.it/FMin/8
Don't make it unnecessarily hard to find your code -- as long as it's small 
you can include it into your mail

Given

> with open('partite.txt', 'r') as f:
>     splitted = [(int(line.split("'")[0]), line) for line in f]
>     splitted.sort()
>     lsorted = [line for (m, line) in splitted]
>     for z in lsorted:
>         print(z)
> 

with partite.txt looking like this

> 74' Kessie'
> 90' + 4' D'alessandro
> 51' Mchedlidze
> 54' Banega
> 56' Icardi
> 65' Icardi
> 14' Sau


Assuming you want to perform a numerical sort on the numbers before the ' 
you can just apply sorted

with open(...) as f:
    print("".join(sorted(f))

as long as all number strings have the same length. 

If that's not the case python's sorted() has decorate-sort-undecorate 
capabilities built in -- no need to do it manually:

with open("partite.txt") as f:
    by_number = sorted(f, key=lambda line: int(line.partition("'")[0]))
    print("".join(by_number))




More information about the Python-list mailing list