I have tried many options to try and get the sort correct with no success. using this piece of code its meant to output a fully sorted list onto winlist.txt but it only sorts by the first integer, so it doesn't sort properly.
def sort():
winfile = list()
with open ('winners.txt') as fin:
for line in fin:
winfile.append(line.strip('\n'))
winfile.sort()
with open('SortWin.txt', 'w+') as fout:
for winfile in winfile:
fout.write(winfile + '\n')
currently this piece code outputs:
11 Tom
2 Tom
20 Ben
20 Tom
21 Ben
But i want the sort to sort with 2 integers instead of only the first one. so that the 2 comes above the 11
Try using the key
argument:
def sort():
winfile = list()
with open ('winners.txt') as fin:
for line in fin:
winfile.append(line.strip('\n'))
winfile.sort(key=lambda x: int(x.split()[0]))
with open('SortWin.txt', 'w+') as fout:
for winfile in winfile:
fout.write(winfile + '\n')
In order to sort the lines by the first column, you have to split them first and then sort accordingly, by supplying the proper key
to sort()
:
import operator
if __name__ == "__main__":
with open("to_be_sorted.txt", "r", encoding="utf-8") as f:
data = [line.split() for line in f.readlines()]
sort_by_first_column = lambda line: int(operator.itemgetter(0)(line))
data.sort(key=sort_by_first_column)
for line in data:
print(" ".join(line))
Your winfile , after reading from winners.txt, contains a list of strings.
That is why the sort() function sort your string alphabetically .
One way, you can split your strings into two-item tuple/list(fastest is split() into list), cast the first item into int.
Now you sort this list. The output will be list of strings by itself.
def get_key(pair):
pair = pair.split()
return int(pair[0])
def sort():
winfile = list()
with open ('winners.txt') as fin:
for line in fin:
winfile.append(line.strip('\n'))
winfile.sort(key = get_key)
with open('SortWin.txt', 'w+') as fout:
for winfile in winfile:
fout.write(winfile + '\n')
because python open
function will return some String
object, so the number like this "11"
but not 11
, you can convert it by int()
, but there are easy way, use pandas
moudle.
I assume your text is this:
11 Tom
2 Tom
20 Ben
20 Tom
21 Ben
1. use third-party (recommend)
first. you should install pandas, pip install pandas
.
pands.read_csv site
import pandas as pd
# sep is Delimiter to use, default is comma
df = pd.read_csv('winners.txt', header=None, names=['num', 'name'], sep=' ', dtype={'num': int, 'name': str})
df = df.sort_index(by='num')
df.to_csv('SortWin.txt', index=False, sep=' ', header=None, mode='w+')
finally, the result like this
2 Tom
11 Tom
20 Ben
20 Tom
21 Ben
2. original python function solution
Don't use third-party, we can do it too.
def sort():
winfile = list()
with open ('winners.txt') as fin:
for line in fin:
winfile.append(line.strip('\n'))
winfile.sort(key=lambda x: int(x.split(' ')[0]))
with open('SortWin.txt', 'w+') as fout:
for winfile in winfile:
fout.write(winfile + '\n')
Firebase Cloud Functions: PubSub, "res.on is not a function"
TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
How to run the maximum number of threads possible on your computer ? I want to run the maximum number of threads in my python codeI run the code on a Windows computer
Input: 'blah move_me2 , nah '
I'm working on Gazebo Sim which uses 'Gstreamer Plugin' to stream Camera Video via UDPSimulation is started on Ubuntu 18