有没有办法解决这个TypeError

时间:2019-10-30 08:35:08

标签: python

我很难弄清楚我的代码出了什么问题。我需要帮助。

next(fhr) # skip header row
customer_list = [] # initialize empty customer list

for line in fhr:
    ls = line.split(',')
    customer_list.append([ls[0], ls[1], ls[2], ls[3], ls[4], ls[5], ls[6], int(ls[7]), ls[8], ls[9], ls[10].strip('\n')])

from operator import itemgetter
customer_list.sort(key=itemgetter(7), reverse=True)
print(customer_list)

writepath = './loan-data-output-v1.csv'
fwh = open(writepath, 'w', encoding='utf-8')
fwh.write('Name' +','+ 'State' +','+'Age' +','+'Annual Income'+','+ 'Loan Type' +','+' Loan Amount' +','+ 'Length of Loan in Years' +','+ 'Days Delinquent' +','+ 'Interest Rate' +','+ 'Number of Loans Prior' +','+'Years as Customer' + '\n')

for i in customer_list:
    if customer_list[i][7] >= 90:
        fwh.write(customer_list[i][0] + ',' + customer_list[i][1] + ',' + customer_list[i][2] + ',' + customer_list[i][3] + ',' + customer_list[i][4] + ',' + customer_list[i][5] + ',' + customer_list[i][6] + ',' + customer_list[i][7] + ',' + customer_list[i][8] + ',' + customer_list[i][9] + ','+ customer_list[i][10] + '\n')
fhr.close()
fwh.close()

我在最后一个for循环中遇到此错误,我不确定该怎么办。有人可以帮忙吗? TypeError:列表索引必须是整数或切片,而不是列表

1 个答案:

答案 0 :(得分:1)

您正在使用列表列表,因此当您使用for i in list_of_list时,i本身就成为列表。

for i in customer_list:
    if i[7] >= '90':
        fwh.write(i[0] + ',' + i[1] + ',' + i[2] + ',' + i[3] + ',' + i[4] + ',' + i[5] + ',' + i[6] + ',' + str(i[7]) + ',' + i[8] + ',' + i[9] + ','+ i[10] + '\n')
fhr.close()
fwh.close()

或者,您可以使用

for i in range(0,len(customer_list)):
    if customer_list[i][7] >= '90':
        fwh.write(customer_list[i][0] + ',' + customer_list[i][1] + ',' + customer_list[i][2] + ',' + customer_list[i][3] + ',' + customer_list[i][4] + ',' + customer_list[i][5] + ',' + customer_list[i][6] + ',' + str(customer_list[i][7]) + ',' + customer_list[i][8] + ',' + customer_list[i][9] + ','+ customer_list[i][10] + '\n')
fhr.close()
fwh.close()

编辑:第二种方法假定customer_list的长度是恒定的,或者换句话说,您在循环期间没有向customer_list添加任何内容。感谢DanielRoseman指出第二个代码中的潜在错误。

编辑2: 感谢quamrana提出了这种建议,

for i in customer_list:
    if i[7] >= '90':
        i[7] = str(i[7])
        fwh.write(','.join(i[0:11]) + '\n')
fhr.close()
fwh.close()