【问题标题】:Python 3 Sorting a List of Tuples? [closed]Python 3 对元组列表进行排序? [关闭]
【发布时间】:2013-11-01 04:48:45
【问题描述】:

我是 Python 新手,我有一个问题。我被告知要与我为同一程序制作的另一篇文章分开提问。这是作业,所以我想要一些指导。我有一个元组列表,我想按 tuple[0] 对其进行排序并返回完整的元组以用于打印到屏幕上。元组由 (score,mark(x or o),index) 组成

这是我的基本代码(井字游戏的一部分-我在另一篇文章中有完整代码):::

listOfScores = miniMax(gameBoard)
best = max(listOfScores, key=lambda x: x[0])

if best[0] == 0:
            print("You should mark " + best[1] + " in cell " + best[2] + ".")
            print("This will lead to a tie.")
        elif best[0] > 0:
            print("You should mark " + best[1] + " in cell " + best[2] + ".")
            print("This will lead to a win.")
        else:
            print("You should mark " + best[1] + " in cell " + best[2] + ".")
            print("This will lead to a loss.")

我收到此错误:::

Traceback (most recent call last):
  File "C:\Users\Abby\Desktop\CS 3610\hw2\hw2Copy.py", line 134, in <module>
    main()
  File "C:\Users\Abby\Desktop\CS 3610\hw2\hw2Copy.py", line 120, in main
    best = max(listOfScores, key=lambda x: x[0])
TypeError: unorderable types: list() > int()

我不确定为什么会这样。这是我第一次尝试使用它:

best = max(listOfScores, key=lambda x: x[0])

所以我认为也许我使用不正确。有没有更好的方法来排序这些元组(从最大到最小,从最小到最大),以便我可以检索最小或最大值?谢谢! :)

【问题讨论】:

标签: python list sorting


【解决方案1】:

如果你想排序它,那么使用sorted() ;)

best = sorted(listOfScores, key=lambda x: x[0])

这会将它从最低分数排序到最高分数。

【讨论】:

    【解决方案2】:

    假设

    listOfScores = [1, 3, 2]
    

    这就是它的完成方式:

    best = max(listOfScores, key=lambda x:x)
    

    这不是 lambda x:x[0]。这将适用于以下情况:

    listOfScores = [[1], [3], [2]]
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 2022-01-25
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 2015-01-28
      相关资源
      最近更新 更多