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>Are you doing an incremental sort or are you only sorting by the <code>a1</code>elements?</p>

<p>If you really need to get a number value for a letter, you can probably use 
<code>string.ascii_letters.index(letter)</code>
Or even better, if you only need consecutive numbers for letters, a&lt;=b, 
use <code>ord(letter)</code>.</p>

<p>But I think letters should sort properly without needing to get an integer value. I think the problem is splitting <code>['a', 'a1']</code>.</p>

<p>I'm not sure if this is what you need:</p>

<pre><code>def sort_func(item):
    try:
        return item[1][1][1]
    except:
        return item[1][1]

# sort by the alphanumeric
vals.sort(key=sort_func)
# sort again by the number
vals.sort(key=lambda i: int(i[1][0]))
# sort again by the first letter
vals.sort(key=lambda i:i[0])
</code></pre>

python list python-2.7 sorting