Sorting a combined list of numbers and letters in Python
<p>I am trying to sort a list in Python, but one containing both letters and numbers in the same term. The problem with using sort on a string is that it doesn't sort the numbers correctly:</p>

<pre><code>2
23
3
</code></pre>

<p>etc</p>

<pre><code>list = [("a", ['8', '0']), ("a", ['7', '0b']), ("a", ['7', '0']), ("a", ['6', '0b']), ("a", ['6', '01']]

new_list = sorted(list, key=lambda i: i[1]) 
# works great on ints.
</code></pre>

<p>The letters need to be sorted as there number equivalent, ie:</p>

<pre><code>a = 1, b = 2, c = 3, d = 4 etc
</code></pre>

<p>hence <code>4.1a</code> == <code>4.11</code></p>

<p>But I need to preserve the letter in the output and not just convert it to an int. Any ideas?</p>

<p>Here is my solution:</p>

<pre><code>def f(s):
    m = {'a': 1,'b': 2,'c': 3,'d': 4,'e': 5,
         'f': 6,'g': 7,'h': 8,'i': 9,'j': 10,
         'k': 11,'l': 12,'m': 13,'n': 14,'o': 15,
         'p': 16,'q': 17,'r': 18,'s': 19,
         't': 20,'u': 21,'v': 22,'w': 23,
         'x': 24,'y': 25,'z': 26}
    result = []
    for l in s:
        try:
            result.append(int(l))
        except ValueError:
            result.append(m[l])
    return result

list = [("a", ['8', '0']), ("a", ['7', '0b']), ("a", ['7', '0']), ("a", ['6', '0b']), ("a", ['6', '01'])]
new_list = sorted(list, key=lambda i: f(''.join(i[1])))

&gt;&gt;&gt; new_list
[('a', ['6', '01']),
 ('a', ['6', '0b']),
 ('a', ['7', '0']),
 ('a', ['7', '0b']),
 ('a', ['8', '0'])]
</code></pre>

<p>The function converts something like '60b' to [6,0,2] (the letters are converted to integers following the mapping dict. Then lambda sorts based on the returned list.</p>

python list python-2.7 sorting