Sean2148
Sean2148

Reputation: 365

Trouble trying to sort list of lists/tuples in Python 3

I have a list of lists containg 2 items, taken from a text file, and I'm trying to sort the outer list by the second item in each inner list (the numbers without num). I've looked at other posts about sorting but I can't manage to get my list to sort, help would be appreciated as I've been trying to find out the issue for hours. The problem is that the sort method is not sorting the varibale data.

Here is my code:

def sortItems(data):
    data.sort(key=lambda x: x[1])
    print(data)


get_file = input(str("Please enter a filename: "))
path = get_file + ".txt"

try:
   file = open(path)
except IOError:
   print('The file could not be opened.')
   exit()

for line in iter(file):
    record = line.strip()
    a_list = []
    a_list.append(record.split())
    sortItems(a_list)

The text file I'm reading from:

num1 3453
num2 234
num3 35676776
num4 45
num5 23354

I'd like the output to look like:

[['num3', '35676776']]
[['num5', '23354']]
[['num1', '3453']]
[['num2', '234']]
[['num4', '45']] 

However my out put is:

[['num1', '3453']]
[['num2', '234']]
[['num3', '35676776']]
[['num4', '45']]
[['num5', '23354']]

Any help is very appreciated as I'm somewhat new to using Python.

Upvotes: 0

Views: 69

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 60974

You are overwriting a_list every iteration of the loop. You want to put everything in the same list, then sort numerically, rather than lexicographically.

get_file = input(str("Please enter a filename: "))
path = get_file + ".txt"

try:
    with open(path) as f  
        a_list = [] # define the list outside the loop, so it doesn't get overwritten
        for line in f:
            record = line.strip()
            a_list.append(record.split())
        a_list.sort(key=lambda x: int(x[1]), reverse=True)
except IOError:
    print('The file could not be opened.')
    exit()

Upvotes: 2

Related Questions