python - 新类没有 setItem 方法

标签 python python-2.7

所以,这是我的代码。

def classMaker(csv):
    csv = csv.split("/n")
    firstLine = csv[0]
    csv = csv[1:]
    class newClass():
        def __init__(self, line):
            self.vars = firstLine
            for i in range(len(line)):
                self[firstLine[i]] = line[i]
    return [newClass(line) for line in csv]

问题是 self[firstLine[i]] = line[i] 中的 AttributeError。它说

AttributeError: newClass 实例没有属性 '__setitem__'

我不知道为什么会导致这个错误。我的目标是接收从 Excel 导出的 csv 文件并根据字段名称自动生成对象名称。

提前谢谢你。

最佳答案

如果你使用collections.namedtuple,你可以一起避免newClass :

CSVRow = namedtuple("CSVRow", firstLine)
return [CSVRow(*line) for line in csv]

这假定 CSV header 将是有效的 Python 标识符(也就是说,如果您有像“Some Value”这样的整体,如果您不处理 firstLine,这将不起作用。

这会让你做这样的事情:

# Let's assume your CSV has a Name field
# and that it is the first column
csv_data[3].Name == csv_data[3][0]
# True

此外,您应该查看 csv module以简化 CSV 处理。

关于python - 新类没有 setItem 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17841441/

相关文章:

python - 如何在 GTK 中更新绘图区域

python - 仅解码 URL 非 ascii 字符

python - 使用 "Strptime()"在 Python 中显示时间

python:使用正则表达式将文档字符串捕获为精确匹配

Python (pip) throw [SSL : CERTIFICATE_VERIFY_FAILED] even if certificate chain updated

python - 霍夫圆示例误差和每个圆的访问半径

python - 每个嵌套列表中的元素数

python - pandas 在创建面板时保留数据类型

python - 为什么 .pyc 文件有时在同一目录中创建,有时在 __pycache__ 子目录中创建?

multithreading - Python在休眠时终止线程