tags:

views:

57

answers:

3

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]

?

+4  A: 

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

NullUserException
why not just `sorted([x[0] for x in list])`? sorted is a reserved word so maybe not best to use as a variable.
Justin Peel
@Justine Peel: It's not a reserved word, it's just the name of a function, but the point still stands.
chpwn
He also asked for reverse: `sorted([x[0] for x in list], reverse=True)`. Also, "list" is a builtin. +1 nonetheless
sdolan
@chpwn, you're right I misspoke. Not reserved, just a function.
Justin Peel
+1  A: 

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.

wheaties
A: 
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])
Tony Veijalainen