5

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! :)

AbigailB
  • 339
  • 3
  • 4
  • 18
  • This is sort of a duplicate of https://stackoverflow.com/questions/10695139/sort-a-list-of-tuples-by-2nd-item-integer-value – kuanb Jun 27 '17 at 01:43

2 Answers2

10

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.

TerryA
  • 58,805
  • 11
  • 114
  • 143
1

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.

Raiyan
  • 1,589
  • 1
  • 14
  • 28