File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Prefer list comprehensions over loops
2+ data = [{'name' : 'Alice' , 'age' : 25 , 'score' : 90 },
3+ {'name' : 'Bob' , 'age' : 30 , 'score' : 85 },
4+ {'name' : 'Charlie' , 'age' : 22 , 'score' : 95 }]
5+
6+ # Using a loop
7+ result = []
8+ for row in data :
9+ if row ['score' ] > 85 :
10+ result .append (row ['name' ])
11+
12+ print (result )
13+
14+ # Using a list comprehension
15+ result = [row ['name' ] for row in data if row ['score' ] > 85 ]
16+
17+ # Generator function to read and process a CSV file
18+ import csv
19+ from typing import Generator , Dict
20+
21+ def read_large_csv_with_generator (file_path : str ) -> Generator [Dict [str , str ], None , None ]:
22+ with open (file_path , 'r' ) as file :
23+ reader = csv .DictReader (file )
24+ for row in reader :
25+ yield row
26+
27+ # Path to a sample CSV file
28+ file_path = 'large_data.csv'
29+
30+ for row in read_large_csv_with_generator (file_path ):
31+ print (row )
You can’t perform that action at this time.
0 commit comments