Python Forum
Need help with sorting lists as a beginner - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Need help with sorting lists as a beginner (/thread-39860.html)



Need help with sorting lists as a beginner - Realist1c - Apr-25-2023

I am trying to sort scores from a list that was put into a text file and then transferred into another list. I have tried two methods (shown below) but both of them seem to sort by the first digit of the number, similar to as if it was a decimal number. How can I fix this to sort the list by the full value of the numbers rather than just the first digit?
Code:
[attachment=2346]
Output:
[attachment=2347]


RE: Need help with sorting lists as a beginner - deanhystad - Apr-25-2023

Please post code as text, not screen shots.

Your list is sorted alphabetically because it is a list of strings that just look like numbers. If you want to sort the list numerically, convert the strings into numbers. You can do this by changing the list items to numbers, or you can use a sorting key that uses the numerical values of the items.
original = [1, 303, 12, 40092, 32, 1002]

# Write list to a file
with open("text.txt", "w") as file:
    for item in original:
        print(item, file=file)

# Read the list from the file
with open("text.txt", "r") as file:
    from_file = file.read().strip().split("\n")

print("Original list", original, " Sorted", sorted(from_file))
print("List from file", from_file)
print("Sorted alphabetically", sorted(from_file))
print("Sorted numerically", sorted(from_file, key=int))
Output:
Original list [1, 303, 12, 40092, 32, 1002] Sorted ['1', '1002', '12', '303', '32', '40092'] List from file ['1', '303', '12', '40092', '32', '1002'] Sorted alphabetically ['1', '1002', '12', '303', '32', '40092'] Sorted numerically ['1', '12', '32', '303', '1002', '40092']
Notice that the list read from the file is full of strings, not ints. Also notice that my list read from file is shorter than yours. Your list contains a blank for the last newline. I removed the trailing newline before splitting the file input.

An alternative is to write the values using a file format that retains their type. In the example below, the list is written to a json file. When reading the file back (load()) no extra steps are required to read the file as a list of ints.
import json

original = [1, 303, 12, 40092, 32, 1002]

# Write list to a file
with open("text.txt", "w") as file:
    json.dump(original, file)

# Read the list from the file
with open("text.txt", "r") as file:
    from_file = json.load(file)

print("Original list", original)
print("List from file", from_file)
Output:
Original list [1, 303, 12, 40092, 32, 1002] List from file [1, 303, 12, 40092, 32, 1002]