【问题标题】:Sorting tuple genereated by list comprehension in python在python中对列表推导生成的元组进行排序
【发布时间】:2015-04-09 06:36:42
【问题描述】:

我在对由列表理解创建的单个元组进行排序时遇到问题。 假设我们有:

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

打印一堆无。

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

【问题讨论】:

  • 你可能创建了一个名为mapsorted的变量,覆盖了同名函数。

标签: python sorting tuples list-comprehension


【解决方案1】:

您可以在创建过程中对元组进行排序:

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 2016-06-01
    • 2015-01-28
    相关资源
    最近更新 更多