使用Python将tuple作为元素的排序列表

2024-04-18 17:40:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个清单如下。你知道吗

[(5,), (2,), (4,), (1,), (3,), (6,), (7,), (8,)]

我如何对列表进行排序以获得

[1,2,3,4,5,6,7,8]

或者

[8,7,6,5,4,3,2,1]

什么?你知道吗


Tags: 列表排序
3条回答

我会给你一个更概括的答案:

from itertools import chain
sorted( chain.from_iterable( myList ) )

它不仅可以排序您所要求的内容,还可以排序任意长度的元组列表。你知道吗

将元组列表转换为整数列表,然后对其排序:

thelist = [(5,), (2,), (4,), (1,), (3,), (6,), (7,), (8,)]

sortedlist = sorted([x[0] for x in thelist])

print sortedlist

codepad上看到了吗

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

相关问题 更多 >