我正在尝试使用csv模块打开一个文本文件,其中我有一些值然后被提取并且填充了两个单独的列表。
这是example.txt文件:
1,2
3,4
6,8
8,2
9,3
当我尝试运行此代码时,在不同的场景中有不同的输出:
with (open('A:\WorkSpace--Python\Plotter\MainSource\example.txt','r')) as egFile:
plot=csv.reader(egFile,delimiter=',')
x=[int(row[0]) for row in plots]
y=[int(row[1]) for row in plots]
在ipython中,当我引用x和y时,它输出y的空列表。
对于x:
[1,3,6,8,9]
对于y:
[]
但是如果我注释掉正在填充x的行,那么引用y会返回相应的列表。
with (open('A:\WorkSpace--Python\Plotter\MainSource\example.txt','r')) as egFile:
plot=csv.reader(egFile,delimiter=',')
'''x=[int(row[0]) for row in plots]'''
y=[int(row[1]) for row in plots]
输出y:
[2,4,8,2,3]
我尝试使用不同的变量名,但结果保持不变。
答案 0 :(得分:4)
csv.reader
是 lazy (意味着它只会根据需要生成数据)迭代器,当你迭代它一次时就会耗尽,就像生成器一样。声明x
后,它是空的。
您可以使用list
实现它以允许多次迭代:
plot = list(plot)
但是,如果您的CSV文件较大,则会占用大量内存,但在这种情况下它并没有真正起作用,因为您要保存x
和{y
中的所有值{1}}无论如何。
另一种选择是:
x = []
y = []
for row in plot:
x.append(int(row[0]))
y.append(int(row[1]))
或
x = []
y = []
for xrow, yrow in plot:
x.append(int(xrow))
y.append(int(yrow))
答案 1 :(得分:0)
根据@Alex的回答,您可以使用显式循环来设置x,y值:
x = []
y = []
with (open('E:\\TEMP\\xy.csv','r')) as egFile:
plots=csv.reader(egFile,delimiter=',')
for row in plots:
x.append(int(row[0]))
y.append(int(row[1]))
print x
print y