1

Hello all. i am learning python recently.

I am having a problem sorting files in numerical order. i have files in order in list:

["1card.txt", "card.txt" , "3card.txt", "52card.txt", "badcard.txt"]

when i simply print the list it doesn't print in order instead it prints: 1card.txt, 10card.txt and so on. so how do i fixed the following code?

file=glob.glob('/directory/*.txt')
sorted(file, key=int)
msvalkon
  • 11,887
  • 2
  • 42
  • 38
user3399326
  • 863
  • 4
  • 13
  • 24
  • Seems that you might want the sort to group by the letters? If so, you should have the letters before the digits, because sort should automatically do that, but I'll offer a version that can swap it. – Russia Must Remove Putin Mar 09 '14 at 20:56
  • thanks all for the reply. you guys r gr8. i found the short cut answer in the link suggested by j.f.sebastian – user3399326 Mar 09 '14 at 21:45

3 Answers3

2

How about:

import re

def tryint(s):
    try:
        return int(s)
    except ValueError:
        return s

def alphanum_key(s):
    return [tryint(c) for c in re.split('([0-9]+)', s)]

def sort_nicely(l):
    return sorted(l, key=alphanum_key)

Then you could do:

>>> file = ["1card.txt", "card.txt" , "3card.txt", "52card.txt", "badcard.txt"]
>>> sort_nicely(file)
['1card.txt', '3card.txt', '52card.txt', 'badcard.txt', 'card.txt']
anon582847382
  • 19,907
  • 5
  • 54
  • 57
0

A simple solution without regular expression could be:

def sort_int(examp):
    pos = 1
    while examp[:pos].isdigit():
        pos += 1
    return examp[:pos-1] if pos > 1 else examp

sorted(files, key=sort_int)

['1card.txt', '3card.txt', '52card.txt', 'badcard.txt', 'card.txt']

Javier
  • 1,027
  • 14
  • 23
0
files = ["1card.txt", "card.txt" , "3card.txt", "52card.txt", "badcard.txt"]

def nat_sort(s):
    '''
    provides a sort mechanism for strings that may or 
    may not lead with an integer
    '''
    for i, c in enumerate(s):
        if not c.isdigit():
            break
    if not i:
        return 0, s
    else:
        return int(s[:i]), s[i:]

files.sort(key=nat_sort)

And now files is a sorted list:

['badcard.txt', 'card.txt', '1card.txt', '3card.txt', '52card.txt']

To sort keeping the similar letters together, do similarly to above:

def nat_sort(s):
    '''
    provides a sort mechanism for strings that may or 
    may not lead with an integer, but groups by strings 
    starting after integers, if any
    '''
    for i, c in enumerate(s):
        if not c.isdigit():
            break
    if not i:
        return s, 0
    else:
        return  s[i:], int(s[:i])

files.sort(key=nat_sort)

And now files returns:

['badcard.txt', 'card.txt', '1card.txt', '3card.txt', '52card.txt']
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
  • hi Aaron. thanks for reply. i wanted to order in 1card.txt,2card.txt,badcard.txt. i did found the shortcut answer. – user3399326 Mar 09 '14 at 21:49