I am new to python and i am facing issues with comparing instances of class objects taken from csv files. I assigned the data of person.csv to class Employee and benefits.csv to class Benefits. Now, I need to comapre the instances of both the classes ie, (emp_id). Here are my two csv files: person.csv:
emp_id sex age
1 Male 25
2 Female 26
3 Male 28
benefits.csv:
emp_id code type
1 A1 1
1 B20 2
1 A10 1
2 B20 2
3 A10 1
3 C2 2
code:
class Benefits():
def __init__(self,emp_id,code,codetype):
super().__init__()
self.emp_id = emp_id
self.code = code
self.codetype = codetype
class Employee():
def __init__(self,emp_id,sex,age):
super().__init__()
self.emp_id = emp_id
self.sex = sex
self.age = age
self.benefits = []
def __repr__(self): # specifies how to display an Employee
return "EMP NO:" + str(self.emp_id) + ",SEX:" + str(self.sex) + ",AGE:" + str(self.age) + ",Benefits:" + str(self.benefits)
def add_benefits(self,ben):
self.benefits.append(ben)
dir = os.path.dirname(__file__)
file1 = open(os.path.join(dir,"person.csv"), 'r')
next(file1)
directory = os.path.dirname(__file__)
file2 = open(os.path.join(directory, "benefits.csv"), 'r')
next(file2)
for line1 in file1:
vals1 = list(map(lambda s: s.strip(),line1.split(",")))
E = Employee(vals1[0],vals1[1],vals1[2])
for line2 in file2:
vals2 = list(map(lambda s: s.strip(),line2.split(",")))
B = Benefits(vals2[0],vals2[1],vals2[2])
if vals1[0] == vals2[0]: #this condition needs to check for all the emp_id's
E.add_benefits(Benefits(vals2[0],vals2[1],vals2[2]))
print(E)
but i am getting output only for the last emp_id as follows:
>>>print(E)
EMP NO:3,SEX:Male,AGE:28,Benefits:[A10,C2]
This should be the Required output:
EMP NO:1,SEX:Male,AGE:25,Benefits:[A1,B20,A10]
EMP NO:2,SEX:Female,AGE:26,Benefits:[B20]
EMP NO:3,SEX:Male,AGE:28,Benefits:[A10,C2]
could anyone help me with the issue. thanks in advance.
This appears to be the trouble spot:
for line1 in file1:
vals1 = list(map(lambda s: s.strip(),line1.split(",")))
E = Employee(vals1[0],vals1[1],vals1[2])
I can see that you're trying to add all 3 lines to your vals1 list, and then print it. The reason only 1 line is showing is because you are redefining both the vals1 and E variables during every iteration . So, instead of adding your data to the list you're actually wiping it out and rewriting it on every pass.
How to fix it:
Create an empty list to store the value of E on every iteration, and print that list at the end of the program, or simply print E at the end of every iteration.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.