Reputation: 13
I would like to know how to order values in a text file based on number, specifically, these numbers in front of the names. The program, in theory, should scan through all the numbers, move the largest one to the top, then repeat with the second largest, if I am correct. Test cases:
000870, Angela
455812, Billy
324192, Clyde
111392, Dom
928144, Erika
I haven't found anything that works with multiple numbers and a string so far, unfortunately. It should end up like this, from highest to lowest:
928144, Erika
455812, Billy
324192, Clyde
111392, Dom
000870, Angela
Upvotes: 1
Views: 68
Reputation: 906
Hamza's answer is perfect. But, I am going to give you another option using Pandas, it is much more efficient for managing comma-separated values; for e.g., if two people have the same numbers, you can then order them by alphabetic values.
import pandas as pd
df = pd.read_csv("data_file.csv", header=None)
df.sort_values(by=[0, 1], inplace=True)
print(df)
Also, pandas
is more convenient if you want something fast. It is actually super faster than python. For me, I would certainly use it.
Upvotes: 0
Reputation: 166
Wow you guys ‘s answer are genius !
But I prefer to do in this way , more easier for me to understand : )
textFile = """
000870, Angela
455812, Billy
111392, Dom
324192, Clyde
928144, Erika
"""
# if every number are with fixed digit
tmpList = textFile.split("\n") # create a tmp list
for i in range(tmpList.count('')): # remove empty string
tmpList.remove('')
tmpList.sort(reverse = True) # sort the list
print(“\n”.join(tmpList)) # you can make a function to return it instead of print
Upvotes: 0
Reputation: 2243
Try:
with open('test.txt') as f:
lines = f.readlines()
lines = [l.split(",") for l in lines]
lines = sorted(lines, key=lambda x: x[0], reverse = True)
lines = [",".join(l) for l in lines]
print(lines)
>> ['928144, Erika',
'455812, Billy\n',
'324192, Clyde\n',
'111392, Dom\n',
'000870, Angela\n']
Upvotes: 3