sorting list of a sentence and number
<p>I have checked several of the answers on how to sort lists in python, but I can't figure this one out.</p>

<p>Let's say I have a list like this:
['Today is a good day,1', 'yesterday was a strange day,2', 'feeling hopeful,3']</p>

<p>Is there a way to sort by the number after each sentence? </p>

<p>I am trying to learn this stuff on my own, so I tried stuff like:</p>

<pre><code>def sortMyList(string):
    return len(string)-1

sortedList = sorted(MyList, key=sortMyList())
</code></pre>

<p>But of course it doesn't work becaue sortMyList expects one parameter.</p>

<p>Since no one has commented on your coding attempts so far:</p>

<pre><code>def sortMyList(string):
    return len(string)-1

sortedList = sorted(MyList, key=sortMyList())
</code></pre>

<p>You are on your way, but there are a few issues. First, the <code>key</code> argument expects a function. That function should be <code>sortMyList</code>. <code>sortMyList()</code> would be the <em>result</em> of <em>calling</em> a function - and besides, your function has a parameter (as it should), so calling it with no arguments wouldn't work. Just refer to the function itself.</p>

<pre><code>sortedList = sorted(MyList, key=sortMyList)
</code></pre>

<p>Next, you need to tell <code>sorted</code> what is actually being compared when you compare two strings. <code>len(string)-1</code> gets the length of the string and subtracts one. This would have the effect of sorting the strings by their length, which isn't what you're looking for. You want the <em>character</em> in the string <em>at that index</em>, so <code>sorted</code> will look at all those characters to form a basis for comparison.</p>

<pre><code>def sortMyList(string):
    return string[len(string)-1]
</code></pre>

<p>Next, you can use a negative index instead of calculating the length of the string, to directly get the last character:</p>

<pre><code>def sortMyList(string):
    return string[-1]
</code></pre>

<p>Next, we'd like to handle multi-digit numbers. It looks like there's a comma right before the number, so we'll split on that, starting from the right (in case the sentence itself has a comma). We only need the first split, so we'll specify a <code>maxsplit</code> of <code>1</code>:</p>

<pre><code>def sortMyList(string):
    return string.rsplit(',', maxsplit=1)[1]
</code></pre>

<p>This will run into a problem: these "numbers" are actually still strings, so when you compare them, it will do so alphabetically, putting "10" before "2" and so on. To fix this, turn the number into an integer before returning it:</p>

<pre><code>def sortMyList(string):
    return int(string.rsplit(',', maxsplit=1)[1])
</code></pre>

<p>Putting it all together:</p>

<pre><code>def sortMyList(string):
    return int(string.rsplit(',', maxsplit=1)[1])

sortedList = sorted(MyList, key=sortMyList)
</code></pre>

python python-3.x