Sorting items in a text file in python -


i've been trying figure out how sort results in text file in order of test scores small task i'm doing using lambda sort function. i'm unsure if best way or not recommended me friend.

the results entered text file so:

    text_file = open("results.txt", "a")     text_file.write("\n")     text_file.write(str(score))     text_file.write(" ")     text_file.write(username)     text_file.write(" ")     text_file.write(userclass)     text_file.close() 

my current sorting system looks this:

with open("results.txt") inf: data = [] line in inf:     line = line.split()     if len(line)==4:         data.append(line)  = sorted(a, key=lambda x: x.modified, reverse=true) 

and text file looks this:

5 test b 4 test b 6 test c 7 test 

(score username userclass)

i sort results in descending order score , i'm not sure correct way go it.

thanks in advance.

if need list element sublists, above answers ok. if need sort results

with open("results.txt") inf: data = [] line in inf:     line = line.split()     if len(line)==3:         data.append(tuple(line)) #append tuple  >>> data #as result of codes [('5', 'test', 'b'), ('4', 'test', 'b'), ('6', 'test', 'c'), ('7', 'test', 'a')] >>> data.sort() >>> data #ascending order [('4', 'test', 'b'), ('5', 'test', 'b'), ('6', 'test', 'c'), ('7', 'test', 'a')] >>> data.sort(reverse=true) >>> data # descending order [('7', 'test', 'a'), ('6', 'test', 'c'), ('5', 'test', 'b'), ('4', 'test', 'b')] 

then whatever want

edit

>>> t in data: ...     print  " ".join(t) ...  7 test 6 test c 5 test b 4 test b 

edit 2.1 avoiding duplicates set()

>>> open('ex4.txt') inf: ...     data = set() ...     line in inf: ...             line = line.split() ...             if len(line)==3: ...                     data.add(tuple(line)) ...  >>> data set([('2', 'test', 'c'), ('0', 'test', 'a'), ('1', 'test', 'a'), ('3', 'test', 'b')]) >>> list(data) [('2', 'test', 'c'), ('0', 'test', 'a'), ('1', 'test', 'a'), ('3', 'test', 'b')] >>>  

edit 2.2 avoiding duplicate records if

>>> open("ex4.txt") inf: ...     data = [] ...     line in inf: ...             line = line.split() ...             if (len(line)==3) , (tuple(line) not in data):  ...                     data.append(tuple(line)) ...  >>> data [('1', 'test', 'a'), ('2', 'test', 'c'), ('3', 'test', 'b'), ('0', 'test', 'a')] 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -