I was working on a somewhat gimmick problem in regard to tuples and finally solved it… but I felt that my coding is really ugly. Is there any pythonic/more simple way? Basically, the question gives you a tuple and that you need to sort tuple, remove numbers from same tuple, and then create an output like this.
OUTPUT = [this, sentence, should, now, make, sense]
At beginning, you have…
t=[(4,'make'),(1,'sentence'),(0,'this'),(3,'now'),(5,'sense'),(2,'should')]
My solution
t=[(4,'make'),(1,'sentence'),(0,'this'),(3,'now'),(5,'sense'),(2,'should')]
def makeList(t):
result = ''
t.sort()
for x, y in t:
result += y +', '
result = result[:-2]
result = ('[' + ', '.join([result]) + ']')
return result
OUTPUT: [this, sentence, should, now, make, sense]
That’s easy:
There are several things to note here:
join. The syntax is the same as for list comprehensions_to denote that we don’t need the first value of the tuple (the number), but only the second part (the word)[]around it. We could also have usedstr.formathere, but I think it looks cleaner this way (in this example)