当我们开始学习Python时,经常会遇到一些不好的实践方法。在本文中,您将学习最佳实践,将您的Python开发人员水平提升到更高的水平。
我记得当我第一次开始学习Python时,犯了很多错误,如果我事先知道了,就可以加快学习曲线。
1- 不要在单行上定义变量。
a = 12b = 56c = 128
通常我们每行定义一个变量;然而,有一种方法可以在一行代码中定义多个变量。
a,b,c = 12,56,128
通过这种简单的方式,我们可以定义多个变量,使代码更易于阅读。
2- 使用*导入模块。
from numpy import *numbers = arange(1,10,step = 10)print(mean(numbers))
通常,我们使用*来调用相应库的模块。但是,如果我们只关心特定库函数,调用所有模块就没有意义。
import numpy as npnumbers = np.arange(1,10,step = 10)print(np.mean(numbers))
导入感兴趣的库,如此,我们可以给它分配一个别名,然后调用我们要使用的方法。
from numpy import arange,meannumbers = arange(1,10,step = 10)print(mean(numbers))
我们也可以直接创新感兴趣的库的函数;这两种方式都不错。
3- 使用“+”来连接。
name,year = "Amado",22print("My name is " + name + " and I am " + str(year) + " years old")
通常,我们总是使用+来连接字符串;然而,它的缺点是不太容易理解。
name,year = "Amado",22print(f"My name is {name} and Im {year} years old")
我们使用格式化字符串字面量,它允许连接变量,而不管变量的性质如何;它还有更好的可读性的优点。
4- 不要使用lambda函数。
def function(x): return x**2 print(function(12))
通常,在创建函数时,我们创建一个常规函数。有时候,我们创建的方法很简单,但是我们会经常使用它。
function = lambda x: x**2print(function(12))
我们可以为同样目的创建一个lambda函数,并将其简化。如果我们要创建的函数不是很复杂,那么使用lambda函数比使用常规的Python函数要好得多。
5- 使用多行代码的if else。
age = 22if age>=18: print('You are of age')else: print('You are not of age')
通常,当我们学习时,我们习惯于以这种方式陈述if else语句;但是,它可以简化为只有一行代码。
age = 22"You are of age" if age>=18 else "You are not of age"
以这种方式,将if-else简化为单行代码,使其更易于理解。
6- 使用多个条件 If 语句。
kepler_third_law = lambda ua: (np.round(np.sqrt(ua**3),1))def calculate_years(planet): planet = planet.lower() if planet == "mercury": ua = 0.387 print(f'水星的年数:{kepler_third_law(ua)}') if planet == "venus": ua = 0.723 print(f'金星的年数:{kepler_third_law(ua)}') if planet == "earth": ua = 1 print(f'地球的年数:{kepler_third_law(ua)}') if planet == "mars": ua = 1.524 print(f'火星的年数:{kepler_third_law(ua)}') if planet == "earth": ua = 1 print(f'地球的年数:{kepler_third_law(ua)}') if planet == "jupiter": ua = 5.208 print(f'木星的年数:{kepler_third_law(ua)}') if planet == "saturn": ua = 9.539 print(f'土星的年数:{kepler_third_law(ua)}') if planet == "uranus": ua = 19.182 print(f'天王星的年数:{kepler_third_law(ua)}') if planet == "neptune": ua = 30.058 print(f'海王星的年数:{kepler_third_law(ua)}') if planet == "pluto": ua = 39.439 print(f'冥王星的年数:{kepler_third_law(ua)}')
通常,我们根据所给条件使用多个 if 语句。这种方法的缺点是需要大量的代码行。
import numpy as npkepler_third_law = lambda ua: (np.round(np.sqrt(ua**3),1))def calculate_years(planet): planet = planet.lower() ua_dict = {'saturn':9.539, 'earth':1, 'mercury':0.387, 'venus':0.723, 'jupiter':5.203, 'uranus':19.182, 'pluto':39.439, 'mars':1.524} years = kepler_third_law(ua_dict[planet]) return f'{planet} 行星的年数:{years}'
我们可以创建一个字典来存储行星的 AU 值,进而通过应用开普勒第三定律计算绕太阳运行所需的年数;通过这种策略,我们可以使代码更加简洁易懂。
7- 不要使用列表推导。
import numpy as npnumbers = np.arange(1,20+1,step = 1)par_numbers = []for number in numbers: if number %2==0: par_numbers.append(number)
通常,如果我们想根据给定条件将元素存储在列表中,我们使用 for 循环;例如,在此情况下,我们想仅存储偶数值。
import numpy as npnumbers = np.arange(1,20+1,step = 1)[n for n in numbers if n % 2 == 0]
使用列表推导,我们可以大大减少代码行数,仅使用一行代码。
8- 不要使用枚举。
names = ['Amado','John','Artemio']last_name = ['Vazquez','Jobs','Lara']for i in range(len(names)): print(f'{names[i]} {last_name[i]}')
假设我们想在屏幕上打印人的名字和姓氏;为此,我们使用函数 range() 来定义索引,然后根据生成的索引打印它。
names = ['Amado','John','Artemio']last_name = ['Vazquez','Jobs','Lara']for i,name in enumerate(names): print(f'{name} {last_name[i]}')
使用枚举函数返回列表对象的索引,因此我们可以保存这个步骤。
9- 不要使用zip
manufacturer = ['英菲尼迪','马自达','日产','宝马']model = ['Q50','马自达6','奥特曼','3系']engine = [3.0,2.5,2.0,2.0]for i in range(len(manufacturer)): print(f'{manufacturer[i]} {model[i]} {engine[i]}')
这里我们犯了类似于前一个的错误,不同之处在于我们想要同时打印出三个列表。
manufacturers = ['英菲尼迪','马自达','日产','宝马']models = ['Q50','马自达6','奥特曼','3系']engines = [3.0,2.5,2.0,2.0]for (manufacturer,model,engine) in zip(manufacturers,models,engines): print(f'{manufacturer} {model} {engine}')
使用zip方法允许我们同时使用多个列表,在使用索引的情况下更加舒适,而且它还有个优点,它更容易理解。
10- Keys()/Items()
consoles_dict = {'PS5':499, 'PS5 Digital':399, 'Xbox Series S':299, 'Xbox Series X':499}consoles_dict.keys() #'PS5','PS5 Digital','Xbox Series S','Xbox Series X'consoles_dict.values() # 499,399,299,499consoles_dict.items()
有时我们会误用字典,尤其是使用访问字典的方法。我们使用keys()来访问它的键,values()用于提取分配给每个键的值,最后,items()允许我们提取两个元素。
for key in consoles_dict: print(key)
如果我们想要访问字典键,只需将循环应用于感兴趣的字典即可。
for key in consoles_dict: print(consoles_dict[key])
如果我们想要访问字典的值,则只需将其名称分配为for循环中的键即可。
for key,value in consoles_dict.items(): print(key,value)
最好使用items()方法,并添加两个值以进行迭代,以便我们可以同时得到键和其值。
11- 不要依赖模块。
sum_ = 0for number in range(1,10+1): sum_ += number print(sum_/10)
有些库可以使生活更加轻松,例如有一个名为numpy的库,用于执行数学计算。有些库可以使生活更加轻松,而不是从头开始编程。例如,在数据科学中有一个非常著名的库,用于执行复杂的计算。
import numpy as npnumbers = np.arange(1,10+1,1)print(np.mean(numbers))
numpy库在进行一些数学计算方面极大地简化了我们的工作,从简单的求和到更复杂的傅里叶变换。
12- 不要使用IN
car_model = "Maxima"if car_model == "Altima" or car_model == "Maxima" or car_model == "Q50" or car_model == "Q60": print('mMdel available')
我们可以支持IN条件语句,而不是使用一个长的条件语句。
car_models = ['Altima','Maxima','Q50','Q60']car_model = "Maxima"'Model avaliable' if car_model in car_models else 'Model not avaliable'
我们创建了一个传统的Python列表,IN运算符将比较我们选择的汽车是否在列表内。我们还依赖单行代码的if-else语句。
这可能会让您感兴趣。
10个您绝不能犯的Pandas错误
本文将回顾初学者在学习Pandas时经常犯的10个最常见的错误…
小猪AI.com
使用Streamlit创建漂亮的应用程序
如果您想将ML项目提升到另一个水平,让不同的用户可以在Web中使用您的ML算法…
小猪AI.com
使用这些技巧消除欠拟合和过拟合
欠拟合和过拟合是我们日常面临的问题,在本文中您将学习最强大的…
小猪AI.com
非常感谢您阅读这篇小文章。我希望您学到了很多,并在您的项目中实践,无论是数据科学、计算机安全还是Web开发。您可以在GitHub上访问存储库。