ricebunny ricebunny - 9 days ago 5
Python Question

How to separate and sort a list of integers and it's associated string?

If I have this:

[(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]


How can I separate the integer from the string and then sort it to get this result:

0 'my'
1 'cat'
2 'ate'
3 'it'

Answer

Try the following:

l = [(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]

for item in sorted(l):
    print("{} '{}'".format(item[0], item[1]))

Output:

0 'my'
1 'cat'
2 'ate'
3 'it'
Comments