python中元组序列怎么排序_Python 3对元组列表进行排序?

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.")

I am getting this error:::

Traceback (most recent call last):

File "C:\Users\Abby\Desktop\CS 3610\hw2\hw2Copy.py", line 134, in

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值