10 bevorzugte Methoden zum Refactoring Ihres Python-Codes

Machen Sie Ihren Python-Code lesbarer und leistungsfähiger



Bild



Python – , , , -, . – . , , Python . 10 , Python.



1. (. .: ) ,



(. .: ) Python: , . , for, . Python – , : [ for x in _ if ]. , . :



>>> #     
>>> numbers = list(range(5))
>>> print(numbers)
[0, 1, 2, 3, 4]
>>> 
>>> #  :
>>> squares0 = []
>>> for number in numbers:
...     if number%2 == 0:
...         squares0.append(number*number)
... 
>>> print(squares0)
[0, 4, 16]
>>> 
>>> #   Python :
>>> squares1 = [x*x for x in numbers if x%2 == 0]
>>> print(squares1)
[0, 4, 16]




, « » « ». : {_: _ for in _}, – { for in _}. :



>>> #  
>>> {x: x*x for x in range(5)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
>>> 
>>> #  
>>> {x*x for x in range(5)}
{0, 1, 4, 9, 16}




2. F-



– , . — . C, %, format, Python.



Python . «f-», « » – .



>>> #   
>>> usd_to_eur = 0.89
>>> 
>>> #  :
>>> print('1 USD = {rate:.2f} EUR'.format(rate=usd_to_eur))
1 USD = 0.89 EUR
>>> print('1 USD = %.2f EUR' % usd_to_eur)
1 USD = 0.89 EUR
>>> 
>>> #   Python :
>>> print(f'1 USD = {usd_to_eur:.2f} EUR')
1 USD = 0.89 EUR


F-



, f-, , C str.format. f- .



3.



– . . , , , , . , . :



>>> #  :
>>> code = 404
>>> message = "Not Found"
>>> 
>>> #   Python :
>>> code, message = 404, "Not Found"




. , . , , .



>>> #    
>>> http_response = (404, "Not Found")
>>> code, message = http_response
>>> print(f'code: {code}; message: {message}')
code: 404; message: Not Found




4.



, , – . , , , (. .: . catch-all method – -, / , . . , . . , , ). – , , -. , Python , , .



>>> #    
>>> numbers = tuple(range(8))
>>> numbers
(0, 1, 2, 3, 4, 5, 6, 7)
>>> 
>>> #  :
>>> first_number0 = numbers[0]
>>> middle_numbers0 = numbers[1:-1]
>>> last_number0 = numbers[-1]
>>> 
>>> #   Python :
>>> first_number1, *middle_numbers1, last_number1 = numbers
>>> 
>>> #  
>>> print(first_number0 == first_number1)
True
>>> print(middle_numbers0 == middle_numbers1)
False
>>> print(last_number0 == last_number1)
True




, middle_numbers0 middle_numbers1 . , ( ) . , , , :



>>> #     
>>> print(middle_numbers0 == tuple(middle_numbers1))
True


-



5.



, « », «-» :=, , ? , , , , , . , :



>>> #    
>>> def get_account(social_security_number):
...     pass
... 
>>> def withdraw_money(account_number):
...     pass
... 
>>> def found_no_account():
...     pass
... 
>>> #  :
>>> account_number = get_account("123-45-6789")
>>> if account_number:
...     withdraw_money(account_number)
... else:
...     found_no_account()
... 
>>> #   Python :
>>> if account_number := get_account("123-45-6789"):
...     withdraw_money(account_number)
... else:
...     found_no_account()




, , , (. .: withdraw_money), . , , , .



, , – account_number . Swift, (. .: ), . accountNumber, , . , , .



if let accountNumber = getAccount("123-45-6789") {
    withdrawMoney(accountNumber)
} else {
    foundNoAccount()
}




6. enumerate



, - . for. , : for in _. , , , enumerate, . , .



>>> #     
>>> students = ['John', 'Jack', 'Jennifer', 'June']
>>> 
>>> #  :
>>> for i in range(len(students)):
...     student = students[i]
...     print(f"# {i+1}: {student}")
... 
# 1: John
# 2: Jack
# 3: Jennifer
# 4: June
>>>
>>> #   Python :
>>> for i, student in enumerate(students, 1):
...     print(f"# {i}: {student}")
... 
# 1: John
# 2: Jack
# 3: Jennifer
# 4: June


enumerate



7. zip/zip_longest



, , . , , , . , Python zip, , . , zip , . :



>>> #        zip
>>> students = ['John', 'Mike', 'Sam', 'David', 'Danny']
>>> grades = [95, 90, 98, 97]
>>> 
>>> #  :
>>> grade_tracking0 = {}
>>> for i in range(min(len(students), len(grades))):
...     grade_tracking0[students[i]] = grades[i]
... 
>>> print(grade_tracking0)
{'John': 95, 'Mike': 90, 'Sam': 98, 'David': 97}
>>> 
>>> #  :
>>> grade_tracking1 = dict(zip(students, grades))
>>> print(grade_tracking1)
{'John': 95, 'Mike': 90, 'Sam': 98, 'David': 97}
>>>
>>> from itertools import zip_longest
>>> grade_tracking2 = dict(zip_longest(students, grades))
>>> print(grade_tracking2)
{'John': 95, 'Mike': 90, 'Sam': 98, 'David': 97, 'Danny': None}


zip



zip – zip, , , . , zip , - . , zip_longest .



Python dict, dict. , zip , .



>>> for student, grade in zip(students, grades):
...     print(f"{student}: {grade}")
... 
John: 95
Mike: 90
Sam: 98
David: 97


zip



8. (. .: )



zip . , ? , . , chain. :



>>> #     
>>> from itertools import chain
>>> group0 = ['Jack', 'John', 'David']
>>> group1 = ['Ann', 'Bill', 'Cathy']
>>> 
>>> def present_project(student):
...     pass
... 
>>> #  :
>>> for group in [group0, group1]:
...     for student in group:
...         present_project(student)
... 
>>> for student in group0 + group1:
...     present_project(student)
... 
>>> #   Python :
>>> for student in chain(group0, group1):
...     present_project(student)




, Python — . , chain , . , chain : , , , zip map ( map), Python.



9.



- , ? , , . . , , , : var = ___true if else ___false. .



>>> #   
>>> from random import randint
>>> def got_even_number():
...     return randint(1, 10) % 2 == 0
... 
>>> #  : 
>>> if got_even_number():
...     state = "Even"
... else:
...     state = "Odd"
... 
>>> state = "Odd"
>>> if got_even_number():
...     state = "Even"
... 
>>> #   Python :
>>> state = "Even" if got_even_number() else "Odd"




10.



Python, . , . , , .



. , . , . , , , . , – , .



>>> #   
>>> def process_data(row_data):
...     pass
... 
>>> #  :
>>> with open('large_file') as file:
...     read_data = file.read().split("\n")
...     for row_data in read_data:
...         process_data(row_data)
...
>>> #   Python :
>>> with open('large_file') as file:
...     for row_data in file:
...         process_data(row_data)






, Python Python, , – , . , Python . – , Python (. .: ), . Python.



, .




All Articles