简体   繁体   中英

Sorting list that has tuple as an element with Python

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM