按列在Python中按字母顺序对列表进行排序

时间:2016-02-28 19:06:51

标签: python sorting csv

我写了一段代码,将数据发送到.csv文件,按名称排序,然后从测验中得到3分。我需要从创建的.csv文件中调用该数据,并按名称,数字和平均值按字母顺序对数据进行排序。但是,当我尝试按字母顺序对名称进行排序时,不会出现任何问题。我对Python很陌生,所以我无法看到我的错误。

这是我的代码中保存和(尝试)打印数据的部分。

if class_number == 2:
    f = open("Class 2" + ".csv", 'a')
    writer = csv.writer(f, delimiter =',')
    writer.writerow([name, count1, count2, count3])
    print ("Your scores were", count1, ",", count2, ", and", count3)

    print("Would you like to see previous results?")
    print("Press 1 to see previous results for your class. Press 2 to close the program")
    answer = int(input())
    if answer == 1:
        print("How would you like data to be sorted?")
        print("Press 1 for alphabetically")
        print("Press 2 for highest to lowest")
        print("Press 3 for average")
        score = input()
        if score == 1:
            sample = open("Class 2.csv", "r")
            csv1 = csv.reader(sample, delimiter=",")
            sort = sorted(csv1, key=operator.itemgetter(0))
            for eachline in sort:
                print("Class 2.csv", "r")

我真的很困惑我做错了什么。

编辑:我需要帮助的部分代码是

if score == 1:
            sample = open("Class 2.csv", "r")
            csv1 = csv.reader(sample, delimiter=",")
            sort = sorted(csv1, key=operator.itemgetter(0))
            for eachline in sort:
                print("Class 2.csv", "r")

这部分不会出于某种原因显示,但没有" If得分"部分它将显示。

2 个答案:

答案 0 :(得分:0)

我用一个带有一列的csv文件对此进行了测试。我假设你只想显示你的结果

import csv
import operator

sample = open("file.csv", "r")
csv_file = csv.reader(sample, delimiter=",")
sort = sorted(csv_file)
for eachline in sort:
    print eachline

答案 1 :(得分:0)

您可以使用字典来保存从csv文件中读取的数据。并使用名称作为关键。然后,您可以对键进行排序,并根据排序的键创建排序列表。以下是使用名称进行排序的示例。

sample = open("example.csv", "r")
csv_file = csv.reader(sample, delimiter=",")

named = {}
for line in csv_file:
    # in case there are multiple entries with same name   
    # assuming names are in the first column
    named[line[0]] = named.get(line[0]) or []
    named[line[0]].append(line)

sorted_name_key = sorted(named)
name_sorted = []
for key in sorted_name_key:
    name_sorted.extend(named[key])

这样您就可以为所需的任何列实现排序。