简体   繁体   中英

How to sort CSV files by alphabet and highest number. Python 3

Here is my code (Sorry, I know it's messy):

import csv
with open('test.csv', 'w', newline='') as fp:
    a = csv.writer(fp, delimiter=',')
    data = [['Bob', '4', '6', '3'],
            ['Dave', '7', '9', '10'],
            ['Barry', '5', '2', '3']]
    a.writerows(data)
print("1 for for alphabetical orderwith each students highest score\n2 for highest score, highest to lowest\n3 for average score, highest to lowest")
cho_two=int(input())
class_a = open("test.csv")
csv_a = csv.reader(class_a)
a_list = []
for row in csv_a:
    row[1] = int(row[1])
    row[2] = int(row[2])
    row[3] = int(row[3])
    minimum = min(row[1:3])
    row.append(minimum)
    maximum = max(row[1:3])
    row.append(maximum)
    average = sum(row[1:3])//3
    row.append(average)
    a_list.append(row[0:9])
if cho_two == 1:
    alphabetical = [[x[0],x[6]] for x in a_list]
    print("\nCLASS A\nEach students highest by alphabetical order \n")
    for alpha_order in sorted(alphabetical):
        print(alpha_order)
        class_a.close()

Here is what is should output:

['Barry', 5]
['Bob', 6]
['Dave', 10]

I want it to output the highest score that the person got in alphabetical order.

It actually outputs this:

['Barry', 2]
['Bob', 3]
['Dave', 5]

Thanks.

You have made a few mistakes here:

First you store the average in the 5 th position then check the list in the 6 th position.

Secondly you don't actually slice the values from the row correctly.

minimum = min(row[1:3])

This only gets the first 2 elements, you need to get all of the elements. I'd suggest reading from 1 onwards with row[1:]

Then you need to fix your code that computes the average:

average = sum(row[1:3])//3

This does not do what you think it does! The difference is between integer division and real division.

Then when you append the row, you probably should append all of it with a_list.append(row) . If you need a copy then slice all of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM