Python 3如何对元组列表进行排序?

2024-04-25 14:42:42 发布

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

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

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

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

所以我想也许我用错了。有没有更好的方法对这些元组进行排序(从最大到最小,从最小到最大),以便我可以检索最小或最大的值?谢谢您!:)


Tags: lambdakeyinyoucellthiswillmax
2条回答

假设

listOfScores = [1, 3, 2]

它就是这样做的:

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

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

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

希望这有帮助。

如果要对其进行排序,请使用^{};)

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

这将从最低分到最高分进行排序。

相关问题 更多 >