Order a list but respect integer ordering (natural sort order)

Python 2, 68 bytes

lambda l:sorted(l,key=lambda x:int(re.sub("\D","",x)or 0))
import re

Try it online!

I used something like this to sort PDF files recently!

my entry originally didn't work but Neil fixed it (thanks!)


Perl 6,  32 31  30 bytes

*.sort(*.comb(/\d+|\D+/)».&val)

Test it

*.sort(*.comb(/\d+|\D/)».&val)

Test it

*.sort(*.comb(/\d+|./)».&val)

Test it

Expanded:

*\                         # WhateverCode lambda (this is the parameter)

.sort(                     # sort by doing the following to each string

  *.comb( / \d+ | . / )\ # split the string into consecutive digits or a character

  ».&val                   # convert each to a Numeric if possible

)

Note:

"Bond007".comb(/\d+|\D+/)».&val
# results in
("Bond", IntStr.new(7, "007"))

# and

"Bond007".comb(/\d+|./)».&val
# results in
("B", "o", "n", "d", IntStr.new(7, "007"))

APL (Dyalog Unicode) 17.0 (currently in alpha), 31 bytesSBCS

Anonymous tacit prefix function taking a list of strings as argument.

⊂⊃¨⍨∘⍋({0::⍵⋄⍎⍵}¨⊢⊂⍨1,2≠/∊∘⎕D)¨

As version 17.0 isn't on TIO yet, here is a test session transcript:

      f←⊂⊃¨⍨∘⍋({0::⍵⋄⍎⍵}¨⊢⊂⍨1,2≠/∊∘⎕D)¨
      ⎕JSON f ⎕JSON '["abc123", "abc6", "abc47", "abd49"]'
["abc6","abc47","abc123","abd49"]
      ⎕JSON f ⎕JSON '["foo0", "bar12", "foobar12", "foo"]'
["bar12","foo","foo0","foobar12"]
      ⎕JSON f ⎕JSON '["Bond007", "Bond07", "Bond7", "Bond12"]'
["Bond007","Bond07","Bond7","Bond12"]
      ⎕JSON f ⎕JSON '["one1", "one11two23", "one1two2", "one1two3", "1"]'
["1","one1","one1two2","one1two3","one11two23"]

 from the entire argument…

⊃¨⍨ pick each of the indices…

 that are…

 the ascending grade (indices which would place in ascending order) of…

( the following tacit function applied to each of the strings:

∊∘⎕D Boolean mask for the characters which are members of the set of Digits

2≠/ pairwise inequality of that (i.e. indicate beginnings of letter runs and digit runs)

1, prepend 1 to mark the first character as beginning a run

⊢⊂⍨ use that to partition (beginning partitions at 1s) the string

{ apply the following anonymous lambda to each partition:

  0:: if any error happens, then:
    return the argument as-is

   try to:
   ⍎⍵ evaluate the argument

Tags:

Code Golf