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 <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.
Assuming that
listOfScores = [1, 3, 2]
This is how its done:
best = max(listOfScores, key=lambda x:x)
It's not lambda x:x[0]. That would apply for a case like :
listOfScores = [[1], [3], [2]]
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With