简体   繁体   English

通过读取 python 中的 CSV 输入来创建对象并将它们添加到列表中

[英]Creating objects and adding them to a list by Reading CSV input in python

This is currently my code for reading through a CSV file, Creating a person object, and adding each person to a list.这是我目前用于阅读 CSV 文件、创建人员 object 并将每个人添加到列表中的代码。 One line Example input: John,Langley,1,2,2,3,5一行示例输入: John,Langley,1,2,2,3,5

When i print(per) each time after creating a person object.当我每次创建一个人 object 后打印(每)。 My output is correct, but as soon as i add that person to the list i made, the numeric values AKA 'traits' for that person are all the same as the last persons traits in the CSV file.我的 output 是正确的,但是一旦我将该人添加到我制作的列表中,该人的数值 AKA 'traits' 与 CSV 文件中的最后一个人的特征相同。

For Example:例如:

John,Langley,1,2,2,3,5 --(add to list)-->John,Langley,1,1,1,1,1约翰,兰利,1,2,2,3,5 --(添加到列表)-->约翰,兰利,1,1,1,1,1

Isabel,Smith,3,2,4,4,0 --(add to list)-->Isabel,Smith,1,1,1,1,1伊莎贝尔,史密斯,3,2,4,4,0 --(添加到列表)-->伊莎贝尔,史密斯,1,1,1,1,1

John,Doe,1,1,1,1,1 --(add to list)-->John,Doe,1,1,1,1,1 John,Doe,1,1,1,1,1 --(添加到列表)-->John,Doe,1,1,1,1,1

This is impacting me with continuing because i need the person objects' traits to be valid in order to perform analysis on them in the next couple methods.这影响了我继续,因为我需要人员对象的特征有效,以便在接下来的几种方法中对它们进行分析。 PLEASE IGNORE MY PRINT STATEMENTS.请忽略我的打印声明。 THEY WERE FOR MY DEBUGGING PURPOSES它们是为了我的调试目的

def read_file(filename):
    file = open(filename, "r", encoding='utf-8-sig')
    Traits_dict = {}
    pl = []
    next(file)
    for line in file:
        line = line.rstrip('\n')
        line = line.split(',')
        first = str(line[0].strip())
        last = str(line[1].strip())
        w = line[2].strip()
        hobby = line[3].strip()
        social = line[4].strip()
        eat = line[5].strip()
        sleep = line[6].strip()
        Traits_dict["Work"] = w
        Traits_dict["Hobbies"] = hobby
        Traits_dict["Socialize"] = social
        Traits_dict["Eat"] = eat
        Traits_dict["Sleep"] = sleep
        per = Person(first, last, Traits_dict)
        print(per)
        pl.append(per)
    print(pl[0])
    print(pl[1])
    print(pl[2])
    print(pl[3])
    print(pl[4])
    return pl

All the Traits_dict = {} are the same to all object since you initiating the dict before the loop so it's giving each Person object the same dict reference in it.所有Traits_dict = {}与所有 object 相同,因为您在循环之前启动了 dict,因此它为每个 Person object 提供了相同的 dict 引用。 You can put the Traits_dict = {} inside the loop that it will create each Person a new dict您可以将Traits_dict = {}放在循环中,它将为每个人创建一个新的字典

for line in file:
    Traits_dict = {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM