gpt4 book ai didi

python - 错误: list index out of range

转载 作者:行者123 更新时间:2023-12-01 05:30:43 25 4
gpt4 key购买 nike

我正在处理 CSV 文件,这是迄今为止我所拥有的。我收到一条错误消息,指出我的索引超出范围。它完成了第一个 for 循环,然后变得困惑。我正在尝试填充字典。

def read_table(file):
line = file.readline()
line = line.strip()
keylist = line.split(',')
d = {}
for key in keylist:
if key not in d:
d[key] = []
while line != '':
line = file.readline()
line = line.strip()
val = line.split(',')
for i in keylist:
index = keylist.index(i)
d[keylist[index]].append(val[index])
return d

最佳答案

只要 line 变空,您的 while 循环就不会中断,它只会在每个循环开始时检查这一点。

因此,当您阅读完除最后一行之外的所有内容后,您可以执行以下操作:

while line != '': # the last line wasn't empty
line = file.readline() # but now this one is
line = line.strip()
val = line.split(',') # so this returns a single value
for i in keylist:
index = keylist.index(i) # so this raises an IndexError
d[keylist[index]].append(val[index])

最小修复是将检查直接放在每个readline之后:

while True:
line = file.readline()
line = line.strip()
if not line:
break
val = line.split(',') # so this returns a single value
for i in keylist:
index = keylist.index(i) # so this raises an IndexError
d[keylist[index]].append(val[index])

(请注意,如果文件中间有空行,您将提前返回而不是引发错误,因为您正在检查 line = line 之后的 line。 strip(),因此您无法再区分空行 '\n' 和文件结尾 ''。如果是这样出现问题,只需将测试向上移动一行即可。)

一个更好的修复方法是迭代文件:for line in file: 完全按照您希望循环执行的操作,而无需处理 readline 并检查空字符串和break循环等等。

但是更好的修复方法是使用 csv模块并让它做它该做的事:

d = defaultdict(list)
reader = csv.DictReader(file)
for line in reader:
for key, value in line.items():
d[key].append(value)
return d

或者,也可以构建一个字典列表(可以使用 list_o_dicts = list(reader) 来完成),然后在最后将其转换为列表字典。

关于python - 错误: list index out of range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20340693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com