在python中对列表理解生成的元组进行排序

时间:2015-04-09 06:36:42

标签: python sorting tuples list-comprehension

我无法对按列表推导创建的单个元组进行排序。 说我们有:

words = [(a, b, c) for a in al for b in bl for c in cl]

现在我想通过执行以下操作对每个元组(a,b,c)进行排序:

map(lambda x: sorted(x), words)

这给了我错误:'tuple'对象不可调用。

我也尝试过:

for i in range(len(words)):
    out = [words[i][0], words[i][1], words[i][2]]
    print out.sort()

打印出一堆Nones。

我错过了什么? 提前谢谢。

1 个答案:

答案 0 :(得分:4)

您可以将元组排序为创建的一部分:

words = [sorted((a, b, c)) for a in al for b in bl for c in cl]

请注意,这将为您提供列表列表,而不是元组列表,因为sorted会返回一个列表。如果你真的想要元组,你将不得不这样做

words = [tuple(sorted((a, b, c))) for a in al for b in bl for c in cl]