Hi all
I am trying to learn about generators. The code below is showing some strange behaviours (the aim is to calculate the average raised Amt for each company in round "a"):
techcruncher.csv:
Would appreciate if someone could explain why is this the case.
Thanks in advance!
I am trying to learn about generators. The code below is showing some strange behaviours (the aim is to calculate the average raised Amt for each company in round "a"):
techcruncher.csv:
Output:permalink,company,numEmps,category,city,state,fundedDate,raisedAmt,raisedCurrency,round
digg,Digg,60,web,San Francisco,CA,01-Dec-06,8500000,USD,b
digg,Digg,60,web,San Francisco,CA,01-Oct-05,2800000,USD,a
facebook,Facebook,450,web,Palo Alto,CA,01-Sep-04,500000,USD,angel
facebook,Facebook,450,web,Palo Alto,CA,01-May-05,12700000,USD,a
photobucket,Photobucket,60,web,Palo Alto,CA,01-Mar-05,3000000,USD,a
file_name = "techcruncher.csv" lines = (line for line in open(file_name)) list_line = (s.rstrip().split(",") for s in lines) cols = next(list_line) company_dicts = (dict(zip(cols,data)) for data in list_line) unique_companies = ( company_dict["company"] for company_dict in company_dicts if company_dict["round"] == ("a".lower()) ) number_of_companies = len(list(unique_companies)) print(number_of_companies)I get the output below, which is what I expect.
Output:PS D:\python> python generatorlearn.py
3
However, when I change the code to this:file_name = "techcruncher.csv" lines = (line for line in open(file_name)) list_line = (s.rstrip().split(",") for s in lines) cols = next(list_line) company_dicts = (dict(zip(cols,data)) for data in list_line) funding = ( int(company_dict["raisedAmt"]) for company_dict in company_dicts if company_dict["round"] == ('A'.lower()) ) total_series_a = sum(funding) print(total_series_a) unique_companies = ( company_dict["company"] for company_dict in company_dicts if company_dict["round"] == ("a".lower()) ) number_of_companies = len(list(unique_companies)) print(number_of_companies)(new lines are 6-12 inclusive), I get the following output:
Output:PS D:\python> python generatorlearn.py
18500000
0
Somehow the generator unique_companies do not seem to work anymore. Would appreciate if someone could explain why is this the case.
Thanks in advance!