Python:列表索引必须是整数,而不是str?

2024-05-19 01:13:31 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有如下代码:

with open(completeCSV, 'r') as csvfile:
    test = csv.reader(csvfile, delimiter=';')
    for line in test:
        print(line)
        i = i + 1  # on the first line, i will equal 1
        count = line[0]
        if count == '1':
            for prof in proflist:  # vertex1=prof
                if line[1].lower() == proflist[prof]:
                    # if vertex1 is a professor, you want to keep the edge.
                    lines_to_keep.append(i)
                    break  # breaks and doesn't check the rest of profs

它基本上读取一个CSV,并检查CSV中的一个值是否等于列表proflist中的另一个值。在

我得到了这个错误:

Traceback (most recent call last): File "C:/Users/sskadamb/PycharmProjects/BetterDelimiter/filter.py", line 50, in if line[1].lower()==proflist[prof]: TypeError: list indices must be integers, not str

是因为proflist[prof]?但是我想检查 proflist反对{}。我该怎么做?我做错了什么?我能不能不迭代一下这样的列表?在


Tags: csvthetocsvfileintestforif
3条回答
for prof in proflist:  #vertex1=prof
        if line[1].lower()==proflist[prof]:

Prof是迭代器,不需要再从列表中访问它!在

^{pr2}$

我想这是你的初衷。在

profproflist的元素,而不是索引。在

替代品

if line[1].lower()==proflist[prof]:

^{pr2}$

@mevius所说的似乎是正确的prof是一个字符串,但没有抓住要点:

for prof in proflist:  #vertex1=prof
        if line[1].lower()==proflist[prof]:

这段代码有点疯狂:您已经用for遍历proflist,这样列表中的每个条目都被分配给循环中的prof。在

所以我想你只想:

^{pr2}$

其中,将prof作为字符串是正确的,而实际上在任何地方都不需要int(prof)。在

相关问题 更多 >

    热门问题