Below code is working fine
class p:
def __init__(self):
self.log={
'name':'',
'id':'',
'age':'',
'grade':''
}
def parse(self,line):
self.log['id']=line[0]
self.log['name']=line[1]
self.log['age']=line[2]
self.log['grade']=line[3].replace('\n',"")
return self.log
obj=p()
with open(r"C:\Users\sksar\Desktop\Azure DE\Datasets\dark.csv",'r') as fp:
line=fp.read()
data=[i.split(',') for i in line.split('\n')]
for i in data:
a=obj.parse(i)
print(a)
Input:
1,jonas,23,A
2,martha,23,B
Output:
{'name': 'jonas', 'id': '1', 'age': '23', 'grade': 'A'}
{'name': 'martha', 'id': '2', 'age': '23', 'grade': 'B'}
Question is: When i make a method call(a=obj.parse(i)) out of the loop, inputs are overwritten and give below as o/p {'name': 'martha', 'id': '2', 'age': '23', 'grade': 'B'}
simply missing the previous records.
How to make a method(parse) call without having to iterate through nested loop(Input data) and feed data to the method call? simply how to get the desired output without for loop...
CodePudding user response:
I dont get why you are trying to avoid an explicit loop. I mean, even if you don't see it in your code, if there is something being iterated, there will be a loop somewhere, and if so, "explicit is better than implicit".
In any case, check this:
with open(r"C:\Users\sksar\Desktop\Azure DE\Datasets\dark.csv",'r') as fp:
[print(obj.parse(x.split(','))) for x in fp.readlines()]