5 examples on how to improve your Python codeПолезные примеры того, как улучшить ваш код на Python
1. Using List Comprehensionssquares = []
for x in range(10):
squares.append(x**2)
print(squares)
2. Using Generatorswith open('example.txt') as f:
for line in (line.strip() for line in f):
print(line)
3. Using the zip() functionnames = ['Pippo', 'Pluto', 'Paperino']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f'{name} is {age} years old')
4. Using DefaultDictfrom collections import defaultdict
s = 'hello world'
d = defaultdict(int)
for c in s:
d[c] += 1
print(d)
5. Using enumerate()fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
print(f'{i}: {fruit}')
Techniques to Write Better Python Code
Улучшение Python-кода
@pythonl