0

I have i txt file that i need to sort the info in by a certain element. this would be the original file

Wheaton,Will,7 Parker,Peter,9 Apple,Adam,1 Jones,Mike,10 Potter,Harry,7 

it the file to be sorted by the third element so that the file will read

Apple,Adam,1 Wheaton,Will,7 Potter,Harry,7 Parker,Peter,9 Jones,Mike,10 

I have tried using

allItems = [] for i in info: data = i.rstrip('\n').split(',') allItems.append(data) allItems.sort(key=lambda x: x[2]) 

but it didnt work. how can i organize by list element. Also will python automatically alphabetize the lines or will I have to do it sepatately

5
  • but neither one works. How did it not work? What was the output you got instead? Commented Jul 19, 2013 at 15:01
  • Have you tried key=itemgetter(2) instead of that lambda? * from operator import itemgetter Commented Jul 19, 2013 at 15:04
  • Your first attempt (at least as posted) switches from data to lists as the thing to sort. Commented Jul 19, 2013 at 15:05
  • nothing changed my file was the same Commented Jul 19, 2013 at 15:05
  • @MartijnPieters I needed the information in the third element regardless of that element being a number or a word. Commented Jul 19, 2013 at 16:05

1 Answer 1

3

You are comparing strings, so '1' < '10' < '7' < '9'. Convert them to int.

with open('info.txt', 'r') as f: data = [line.split(',') for line in f] print(sorted(data, key=lambda x: int(x[2]))) 
Sign up to request clarification or add additional context in comments.

10 Comments

I need it sorted in the file not printed
I think you may have to read the data, sort it and then write back.@derpyherp
how would I sort it, the same way I tried before? And how would I write it back afterwards
The sort method I have given in my answer. Basically you should add a int() so you can sort by the number correctly. As for writing back, with open(file, 'w') as f: f.write('\n'.join(data))@derpyherp
I have told you in the above comment. You should first use '\n'.join to make the list a string. f.write('\n'.join(sorted(data, key=lambda x: int(x[2]))))@derpyherp
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.