Home > Enterprise >  How to sort an array of records into descending order
How to sort an array of records into descending order

Time:09-22

I have a csv file called sample.csv that I have converted into a record, this record is set up with an string value and a integer value like so:

[Name,10]
[Name1,12]
[Name2,14]

I would like to be able to sort these records into descending order and then eventually print the names and scores of the three highest scoring pupils and also the name and score of the lowest scoring pupil.Here is my code so far, I am unable to sort the records by integer value.

import csv
file = open("sample.csv")
csvreader = csv.reader(file)
rows = []
for row in csvreader:
    rows.append(row)
file.close()

sortedFile=[]

sortedFile=sorted(rows, key=lambda rows: rows[1])

print(sortedFile)

Edit:

A really helpful person commented but now for whatever they have deleeted their comment.

import csv
file = open("sample.csv")
csvreader = csv.reader(file)
rows = []
for row in csvreader:
    rows.append(row)
file.close()

sortedFile=[]

sortedFile=sorted(rows, key=lambda rows: int(rows[1]))[::-1]

print(sortedFile[0])
print(sortedFile[1])
print(sortedFile[2])
print(sortedFile[-1])

My code now looks like this and I am nearly finished, I believe I am missing something really simple, all I would like is the some text near the array saying

"The person with the highest score is", (name[0]),"with a score of,(score[0])
"The person with the highest score is", (name[1]),"with a score of,(score[1])
"The person with the highest score is", (name[2]),"with a score of,(score[2])
"The person with the lowest score is", (name[-1]),"with a score of,(score[-1])

CodePudding user response:

Maybe something like:

 sortedFile = sorted(rows, key=lambda rows: int(rows[1]))? 

CodePudding user response:

Assuming your data is in a list, you can call sort with key argument to specify how to sort the list. In this case, you can use negative value -x[1] to sort it in reverse order.

data = [['Name',10],
['Name1',12],
['Name2',14]]

data.sort(key = lambda x: -x[1])

Result:

[['Name2', 14], ['Name1', 12], ['Name', 10]]

CodePudding user response:

I recommend the following changes:

import csv

with open("sample.csv", 'r') as file:
    csvreader = csv.reader(file)
    sortedFile = sorted(csvreader, key=lambda rows: int(rows[1]), reverse=True)

print(sortedFile)

for (i,place) in zip([0,1,2,-1], ['highest', '2nd highest', '3rd highest', 'lowest']):
    print('The person with the {} score is {} with a score of {}.'.format(place, sortedFile[i][0], sortedFile[i][1]))

Example input sample.csv

Alice,12
Max,11
Medhi,18
Chen,17
Sasha,15

Example output

[['Medhi', '18'], ['Chen', '17'], ['Sasha', '15'], ['Alice', '12'], ['Max', '11']]
The person with the highest score is Medhi with a score of 18.
The person with the 2nd highest score is Chen with a score of 17.
The person with the 3rd highest score is Sasha with a score of 15.
The person with the lowest score is Max with a score of 11.

CodePudding user response:

You sort in your code in ascending order, and from the condition it is necessary in descending order.

Try this option:

Code:

rows=[['A',10],
['B',12],
['C',11]]

sortedFile=sorted(rows, key=lambda rows: int(rows[1]))[::-1]

if len(sortedFile) > 1:    
    print(sortedFile)
    for i in range(len(sortedFile) - 1):
        print(sortedFile[i])
    print(sortedFile[-1])
elif len(sortedFile) == 1:
    print(sortedFile)
    print(sortedFile[0])
else:
    print('list is empty')

This code takes into account 3 conditions. If the list length is greater than 1, it is equal to 1 and is equal to 0.


For a beautiful output, you can use f-strings, that is, for example, like this:

print(f'The person with the highest score is {name[0]}, with a score of {score[0]}')

I'll show you by my own example:

if len(sortedFile) > 1:
    for i in range(len(sortedFile) - 1):
        print(f'The person with the highest score is {sortedFile[i][0]}, with a score of {sortedFile[i][1]}')
    print(f'The person with the highest score is {sortedFile[-1][0]}, with a score of {sortedFile[-1][1]}')
elif len(sortedFile) == 1:
    print(f'The person with the highest score is {sortedFile[0][0]}, with a score of {sortedFile[0][1]}')
else:
    print('list is empty')
  • Related