I have a list as follows.
[(5,), (2,), (4,), (1,), (3,), (6,), (7,), (8,)]
How can I sort the list to get
[1,2,3,4,5,6,7,8]
or
[8,7,6,5,4,3,2,1]
?
I have a list as follows.
[(5,), (2,), (4,), (1,), (3,), (6,), (7,), (8,)]
How can I sort the list to get
[1,2,3,4,5,6,7,8]
or
[8,7,6,5,4,3,2,1]
?
Convert the list of tuples into a list of integers, then sort it:
thelist = [(5,), (2,), (4,), (1,), (3,), (6,), (7,), (8,)]
sortedlist = sorted([x[0] for x in thelist])
print sortedlist
See it on codepad
I'll give you an even more generalized answer:
from itertools import chain
sorted( chain.from_iterable( myList ) )
which can sort not only what you've asked for but also any list of arbitrary length tuples.
datalist = [(5,), (2,), (4,), (1,), (3,), (6,), (7,), (8,)]
sorteddata = sorted(data for listitem in datalist for data in listitem)
reversedsorted = sorteddata[::-1]
print sorteddata
print reversedsorted
# Also
print 'With zip', sorted(zip(*datalist)[0])