2

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]

?

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

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

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.

Comments

0
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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.