早期引用作为列表中断我的读取数据集导入的csv文件行?

2024-06-02 06:30:21 发布

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

我正在打开、读取csv文件(https://www.kaggle.com/ramamet4/app-store-apple-data-set-10k-apps)的内容并将其存储到列表数据结构中。 我尝试将数据集的头和其余部分存储在两个独立的变量中,试图避免繁琐的foo=list(bar),而是做了类似foo=list(bar)[0]的操作。在我尝试对数据集的其余部分或另一行执行相同的操作之前,这一切都很正常。使用slice不会给出任何错误,但仍然得到一个空变量,使用foo=list(bar)[1]给出一个“索引超出范围”异常。如果我在[0]之前引用了[1],我就不会对索引有任何抱怨,我不明白为什么会发生这种情况

使用Jupyter笔记本

`from csv import reader
     oDs1 = open('AppleStore.csv')
     oDs2 = open('googleplaystore.csv')
     rDs1 = reader(oDs1)
     rDs2 = reader(oDs2)
     header = list(rDs1)[0] #everything is fine here, no matter which index 
     #number I choose
     print(*header)
     restofDataSet = list(rDs1)[1:3] #short slice for test, no error but 
     #variable is empty
     print(*restofDataSet)
     firstRow= list(rDs1)[1] #python raise error`

我希望为我的头和数据集的其余部分(或至少另一个测试行)变量赋值,但我在slice方法上得到空数据集,并且在引用第一个([0])之后的另一个索引时出现以下错误:

IndexErrorTraceback (most recent call last) <ipython-input-16-0baa98682a7a> in <module>()
      8 restofDataSet = list(rDs1)[1:3]
      9 print(*restofDataSet)
---> 10 firstRow= list(rDs1)[1]
     11 

IndexError: list index out of range

Tags: csv数据foo错误barsliceopenlist