1

我正在获取一个带有标题行(称为aggregate_file)的 csv 文件,按列对其进行排序,然后将其重新写入另一个 csv 文件(称为sorted_file)。我要排序的列标题由variable_names.

def sortbyCounty(aggregate_file, sorted_file, *variable_names): 
    f = open(aggregate_file, 'r')
    readit = csv.reader(f) 
    headers = readit.next()
    col_indices = []
    for var in variable_names: 
         col_indices.append(headers.index(var))
    print col_indices
    thedata = list(readit)
    thedata.sort(key=operator.itemgetter(col_indices))
    fx = open(sorted_file, 'w') 
    writeit = csv.writer(fx)
    writeit.writerow(headers)
    writeit.writerows(thedata)
    writeit.close()
    return sorted_file

接下来,我在以下几行中调用此函数:

aggregate_file = "Aggregate_test90.csv"
sorted_file = "County_test90.csv"
variable_names = 'CTYCODE90'
test = sortbyCounty(aggregate_file, sorted_file, *variable_names)

这是我的错误信息:

col_indices.append(headers.index(var))
ValueError: list.index(x): x not in list

但是,当我列出print我的headers列表时,我可以清楚地看到我的变量存在:

['_STATE90', 'HEIGHT90', 'WEIGHT90', '_BMI90', 'AGE90', 'CTYCODE90', 'IYEAR90', 'SEX90', '_RFOBESE90']

所以我完全不明白为什么我会收到此错误消息。我错过了什么?

4

1 回答 1

2

variable_names应该是一个listtuple字符串。由于字符串的行为也类似于序列,因此*onvariable_names将您的函数调用变为:

sortbyCounty(aggregate_file, sorted_file, 'C', 'T', 'Y', 'C', 'O', 'D', 'E', '9', '0')

当您明确希望函数调用如下时:

sortbyCounty(aggregate_file, sorted_file, 'CTYCODE90')

制作variable_names一个字符串列表或元组应该这样做。

于 2012-08-11T05:36:15.973 回答