Python 3对元组列表进行排序? [英] Python 3 Sorting a List of Tuples?

查看:226
本文介绍了Python 3对元组列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python新手,我有一个问题.有人告诉我要问这个问题,与我为同一程序撰写的另一篇文章分开问.这是家庭作业,所以我只需要一些指导.我有一个元组列表,我想按tuple [0]对其进行排序,然后将要打印的完整元组返回到屏幕.元组由(得分,标记(x或o),索引)组成

I am a Python newbie and I have a question. I was told to ask this separately from another post I made for the same program. This is homework, so I would just like some guidance. I have a list of tuples, and I want to sort it by tuple[0] and return the full tuple for use in printing to the screen. The tuples are made up of (score,mark(x or o),index)

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

Here is my basic code (part of a tic tac toe game- I have the full code in another post):::

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

我不确定为什么会这样.这是我第一次尝试使用此功能:

I'm not sure why this is happening. This is my first time trying to use this:

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

所以我认为也许我使用不正确.是否有更好的方式对这些元组进行排序(从最大到最小,从最小到最大),以便我可以检索到最小或最大值?谢谢! :)

so I think that maybe I am using it incorrectly. Is there a better way to sort these tuples (from largest to smallest, and smallest to largest), so that I can retrieve either the smallest or largest value? Thank you! :)

推荐答案

如果要对其进行排序,请使用

If you want to sort it, then use sorted() ;)

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

这会将其从最低得分到最高得分进行排序.

This will sort it from the lowest score to the highest.

这篇关于Python 3对元组列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆