Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort output result of python code?

I have this code and try to sort the output print result

# -*- coding: utf-8 -*-

from os import path as os_path, listdir as os_listdir


GETPath = os_path.join('/home/usr/Desktop/fonts')

fonts = []
for fontName in os_listdir(GETPath):
    fontNamePath = os_path.join(GETPath, fontName)
    if fontName.endswith('.ttf') or fontName.endswith('.otf'):
        fontName = fontName[:-4]
        fonts.append((sorted(fontNamePath), sorted(fontName)))

But I can not get the sort lines I have got this result

nmsbd
/home/usr/Desktop/fonts/nmsbd.ttf
font_default
/home/usr/Desktop/fonts/font_default.otf
best_font1
/home/usr/Desktop/fonts/best_font1.ttf
NotoNaskhArabic
/home/usr/Desktop/fonts/NotoNaskhArabic.ttf
best_font2
/home/usr/Desktop/fonts/best_font2.ttf
arabic_k
/home/usr/Desktop/fonts/arabic_k.ttf
arabic_beirut
/home/usr/Desktop/fonts/arabic_beirut.ttf
NotoSansArabic
/home/usr/Desktop/fonts/NotoSansArabic.ttf
ae_almateen
/home/usr/Desktop/fonts/ae_almateen.ttf

How to solve this code ?!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First create a list of tuples [(fontPath, fontName), ...] and afterwards sort them by the name:

GETPath = os_path.join('/home/usr/Desktop/fonts')

fonts = []
for fontName in os_listdir(GETPath):
    fontNamePath = os_path.join(GETPath, fontName)
    if fontName.endswith('.ttf') or fontName.endswith('.otf'):
        fontName = fontName[:-4]
        fonts.append((fontNamePath, fontName))
fonts = sorted(fonts, key=lambda x: x[1])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading