python - 排序由python中的列表理解生成的元组

标签 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)

这给了我错误:“元组”对象不可调用。

我也试过:

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

它打印了一堆 Nones。

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

最佳答案

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

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]

关于python - 排序由python中的列表理解生成的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29531437/

相关文章:

jquery - 同时使用 jQuery 和 FormEncode 验证表单而不重复

c - 使用两个堆栈在 C 中按升序对堆栈进行排序

Python变量怪异?

Python - 'tuple' 对象不支持项目分配

java - 按属性 java 对列表中的帖子进行排序

Python - TypeError : tuple indices must be integers or slices, 不是 str

python - 使用我自己的语料库了解 scikit-learn 的 accuracy_score?

python - 调整大小不会影响 PyQt5 中的布局

python - 在装饰器中扩展 Python 中的类

python - 通过将列表转换为集合然后再转换回列表来对列表进行排序的时间复杂度