首页 > 解决方案 > 将每行中的多个 csv 元素读取到单独的列表中

问题描述

我有一个 CSV,我想将每行的第 6 个元素读入一个列表,并将每行的第 7 个元素读入另一个列表。下面是我的代码:

import csv
import math

#open csv file and create fie reader
with open('weightheightdata.csv', 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')

    #skip first 2 lines (header lines)
    next(reader)
    next(reader)

    #create list of e values using the 9th column of each row
    actualWeight = []
    predictedWeight = []
    for row in reader:
        actualWeight.append(float(row[6]))
        predictedWeight.append(float(row[7]))

我收到错误:TabError: inconsistent use of tabs and spaces in indentation 在线:predictedWeight.append(float(row[7]))

标签: pythonlistcsvfilereader

解决方案


您的代码运行良好。我自己测试过。只需检查您的缩进就行了。确保您使用了与整个文件相同的制表符或 4 个空格。这实际上就是错误的全部。Python 对缩进非常严格。


推荐阅读