python - 为什么我的迭代器在 python3 中返回超出范围?
问题描述
谁能知道为什么这段代码会返回一个超出范围的列表?我正在处理的数据有 20 多列……我哪里出错了?
import itertools
import csv
from reportlab.pdfgen import canvas
file2 = csv.reader(open('file2_dumy.csv','r'))
file1 = csv.reader(open('file1_data.csv','r'))
import itertools
list1 = csv.reader(open('file2_dumy.csv','r'))
list2 = csv.reader(open('file1_data.csv','r'))
canv = canvas.Canvas('der.pdf')
for i,x in itertools.zip_longest([a for a in list2][1:], [b for b in list1][1:],fillvalue='null'):
a = i[0]
b = i[1]
c = i[2]
d = x[0]
e = x[1]
f = x[2]
g = x[3]
canv.drawString(50,700,a)
canv.drawString(120,700,b)
canv.drawString(200,700,c)
canv.drawString(350,700,d)
canv.drawString(450,700,e)
canv.drawString(120,600,g)
canv.showPage()
canv.save()
错误。
Traceback (most recent call last):
File "D:\Python\PyQt5\Backup\SRMS\iterables question sample.py", line 18, in <module>
g = x[3]
IndexError: string index out of range
file2_dumy.csv
解决方案
我刚刚运行它没有错误(python3.6.10)。导入 csv 导入 itertools
for i,j in itertools.zip_longest(csv.reader(open('foo.csv','r')),csv.reader(open('bar.csv','r')), fillvalue='null'):
print(i[3], j[3])
foo.csv:
1,2,3,4,
5,6,7,8,
bar.csv:
1,2,3,4,
5,6,7,8,
4,4,4,4,
输出:
4 4
8 8
l 4
人们可能会讨论“null”是否是一个合适的填充值,但没有错误。如果 CSV 中的所有行至少有 4 列,则应该没有问题。
我怀疑您使用不同的填充值(较短的填充值)生成了错误。无论如何,您应该考虑以下几点:
- 你的 csv 文件真的可以有不同的长度吗?
- 如果是,您是否真的需要
zip_longest
,因为您必须生成数据来填充较小的数据?也许您想使用 justzip
,然后剪切较长的数据集。 - 如果您决定要填充数据,则应使用 eg
[0,0,0,0]
而不是'null'
.