简体   繁体   中英

Python data related error: list indices must be integers or slices, not str

I am trying to automate a process for my job. I keep getting:

Traceback (most recent call last):
Number of UPN's: 
  File "C:/Users/Ultrarev/Desktop/Emeran-Parser/Eme_Parser.py", line 63, in <module>
74
    if rowExcel[0] == kPN[i]:
TypeError: list indices must be integers or slices, not str.

As an error and though I am new to Python I do not know how to approach this with out staring at the screen. I want to make a dictionary of product numbers to cars of interest(ie the car(s) the parts can fit into) object. That object will in turn generate respective cars that can fit that particular part.

import csv
import collections
import sys

from Car_of_Interest import Car_of_Interest


def main ():

    data = csv.open(r"C:\Users\Ultrarev\Desktop\Duplicator-fier\Book1.csv")
    data = csv.reader(data)

    print("Data: (testing)")

def f7(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x in seen or seen_add(x))]

with open(r'C:\Users\Ultrarev\Desktop\Duplicator-fier\Book1.csv', newline = '') as csvfile:
    data = csv.reader(csvfile)
    rowExcel = []
    kPN = []
    car_info = []
    UPN = ()
    cUPN = []
    CARS = {}
    #UPN_len = len(UPN)
    for row in data:
        open(r'C:\Users\Ultrarev\Desktop\Duplicator-fier\Book1.csv')
        rowExcel.append(row)

        car_info.append(row[2])
        car_info.append(row[3])
        car_info.append(row[4])

        #print('-> '.join(row))
    for row in rowExcel:
        kPN.append(row[0])

# Convert to string.
list1 = kPN
str1 = ' '.join(str(e) for e in list1)

#Remove Duplicates in kPN.
UPN = f7(kPN)


l = UPN.__sizeof__()

print("kPN: ")
print(kPN)
print("Data: ")
print(data)
print("UPN: ")
print(UPN)
print("Major Car Information of File to be Parsed into HTML: ")
print(rowExcel)
print("Number of UPN's: ")
print(len(UPN))

for i in kPN:
    for x in rowExcel:
        if rowExcel[0] == kPN[i]:
           #Create Dictionary - UPN:[car...n]
           #Make car objects.
           Car_of_Interest(rowExcel[2], rowExcel[3], rowExcel[4])

#    cars_I
#     ^   
#     |
#UPN:[Car_of_Interest...n]

error

for i in kPN:
    for x in rowExcel:
        if rowExcel[0] == kPN[i]:

I am guessing in the above you want i not kPN[i]

you are already getting the value out of kPN with the for i in kPN loop.

kPN is a vector, if you use for i in kPN , each i is an element of kPN

Try this:

for i in kPN:
    for x in rowExcel:
        if rowExcel[0] == i:

or

for i in range(len(kPN)):
    for x in rowExcel:
        if rowExcel[0] == kPN[i]:
           ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM