Home > database >  How to sort output result of python code?
How to sort output result of python code?

Time:02-25

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 ?!

CodePudding user response:

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])

CodePudding user response:

Are you trying to sort the list that you are appending each entry to? If so, the issue is that you are using sorted on the string itself and not on the entire list. I.e if you want to sort your list and print it, you can do something like this instead:

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)
print(sorted(fonts))

CodePudding user response:

If I recall method sorted() requires assigning to a new variable but sort() does sorting on the existing one. So applying below might help enter image description here

  • Related