使用python在csv文件中排序数据时“列出索引超出范围”错误

时间:2015-03-20 15:48:40

标签: python sorting csv

我有三个.csv文件,我希望python对它们中的数据进行排序。我有这个代码但是当我启动它时会发生错误。此行中发生错误sort = sorted(csv1,key = operator.itemgetter(1))。最后的数字假设选择列但不是。我在Mac上安装了这个程序,但是当我在Windows上启动它时它停止了工作。

import operator
import csv

decision= input("How would you like to view information? Type score or surname.")
decision1= input("What calss would you like to see? Type class1 or class2 or class3.")


if (decision == 'score' and decision1 == 'class1'):
    sample = open('class1.csv', 'r')
    csv1 = csv.reader(sample,delimiter = ',')
    sort = sorted(csv1, key= operator.itemgetter(0))
    for eachline in sort:
        print (eachline)

if (decision == 'surname' and decision1 == 'class1'):
    sample = open('class1.csv', 'r')
    csv1 = csv.reader(sample,delimiter = ',')
    sort = sorted(csv1, key= operator.itemgetter(1))
    for eachline in sort:
        print (eachline)

if (decision == 'score' and decision1 == 'class2'):
    sample = open('class2.csv', 'r')
    csv1 = csv.reader(sample,delimiter = ',')
    sort = sorted(csv1, key= operator.itemgetter(0))
    for eachline in sort:
        print (eachline)

if (decision == 'surname' and decision1 == 'class2'):
    sample = open('class2.csv', 'r')
    csv1 = csv.reader(sample,delimiter = ',')
    sort = sorted(csv1, key= operator.itemgetter(1))
    for eachline in sort:
        print (eachline)

if (decision == 'score' and decision1 == 'class3'):
    sample = open('class3.csv', 'r')
    csv1 = csv.reader(sample,delimiter = ',')
    sort = sorted(csv1, key= operator.itemgetter(0))
    for eachline in sort:
        print (eachline)

if (decision == 'surname' and decision1 == 'class3'):
    sample = open('class3.csv', 'r')
    csv1 = csv.reader(sample,delimiter = ',')
    sort = sorted(csv1, key= operator.itemgetter(1))
    for eachline in sort:
        print (eachline)

2 个答案:

答案 0 :(得分:1)

这样的东西?

import operator
import csv

sorter = raw_input("Set sort method (score or surname): ")
classNumber = raw_input("Set class number (1, 2 or 3): ")

def print_sorted(sortMethod, classNumber):
    classFile = 'class' + str(classNumber) + '.csv'
    with open(classFile, 'r') as fh:
        csvData = csv.DictReader(fh)
        sortedCsvData = sorted(csvData, key=operator.itemgetter(sortMethod))
        for line in sortedCsvData:
            print line

print_sorted(sorter, classNumber)

您可能希望在运行该函数之前添加对用户输入集的某种验证。

如果列中缺少值,则不会出现错误。

编辑说:如果您使用的是python 3,则需要将raw_input()更改为input()

答案 1 :(得分:0)

听起来你的行中至少有一行缺少第1列的值。csv.reader(sample)返回列表生成器,其中每个列表对应一行,每个列表的长度对应于给定行中以逗号分隔的值。所以文件包含这样的数据:

   John,Smith
   Joe
   Jane,Doe

(["John", "Smith"], ["Joe"], ["Jane", "Doe"])解析后会给您csv.reader

sorted尝试从其中一个不存在的列表(行)访问索引(列)时,operator.itemgetter函数正在中断。如果您在上面的示例中对第1列进行排序,则代码会中断,因为列表中只有1个元素["Joe"]