0

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'
Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62
ricebunny
  • 3
  • 1

5 Answers5

0

Try this:

    x = sorted([(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')])
    for i in x:
       print(i)

output:

(0, 'my')
(1, 'cat')
(2, 'ate')
(3, 'it')
Taufiq Rahman
  • 5,600
  • 2
  • 36
  • 44
0

Pythonic way, how sorting, itemgetter from documentation: "return a callable object that fetches item"

L = [(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]
from operator import itemgetter
print ( "\n".join(map(lambda x: "%d '%s'" % x, sorted(L, key=itemgetter(0)))))

you get,

0 'my'
1 'cat'
2 'ate'
3 'it'
Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62
0

Simply sort the list of tuples, and the print them formatted:

>>> tuples = [(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]
>>> tuples = sorted(tuples)
>>> for tup in tuples:
    print("{} '{}'".format(*tup))


0 'my'
1 'cat'
2 'ate'
3 'it'
>>> 
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
0

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'
ettanany
  • 19,038
  • 9
  • 47
  • 63
0

I found an answer to your question on ... How can I sort a dictionary by key?

Using that code, I developed the following:

#!/usr/bin/python3
# StackOverflow answer sample to question:
# How to separate and sort a list of integers and it's associated string?
# Author: RJC (aka mmaurice)
# Question input: [(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]
# Question expected output: 
# 0 'my'
#
# 1 'cat'
#
# 2 'ate'
#
# 3 'it'
import collections
test_dict = dict([(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')])
print(test_dict) #not in order
#use collections to sort the dictionary.
od_test_dict = collections.OrderedDict(sorted(test_dict.items()))
for k, v in od_test_dict.items(): print(k, v)

Hope this helps

Community
  • 1
  • 1
MMaurice
  • 11
  • 2