-7

I am having trouble figuring out what is wrong with my code. I need help.

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()

I am getting this error for the last for loop and I'm not sure what to do about it. Can someone help. TypeError: list indices must be integers or slices, not list

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895

1 Answers1

1

You are using lists of lists so when you use for i in list_of_list, i itself becomes a list..

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()

Alternatively you can use,

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()

EDIT: Second method assumes that your length of customer_list is constant or in other words you are not adding anything to customer_list during the loop. Thanks to DanielRoseman for pointing out potential bug in second code..

EDIT 2: Thanks to quamrana for suggesting this way,

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()
Yash Patel
  • 125
  • 8