Skip to content

Commit e524ef8

Browse files
authored
Create main.py
1 parent 494a09f commit e524ef8

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

better-python/main.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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)

0 commit comments

Comments
 (0)