10个简洁的Python编码技巧_10个简洁的Python编码技巧

Python是一种十分简洁而又美丽的语言,它提供了多种方法来完成相同的任务,这使我们很容易沉醉于它。但是一些不好的习惯也会破坏Python的简洁,很容易让事情变得更复杂。下面是10个小编推荐的编程小技巧,让我们的Python代码更漂亮。

 

1. 学会使用文档字符串

 

使用"""三重双引号"""来编写文档字符串,这些文档字符串可以清楚地说明函数,模块和程序的全部目的。

  •  
def get_percent_sales(product,sales,region):“““Return the product Sales volumes in percent of total in country.Get percentage of product sales of the region.This function gets the product and corresponding sales by region and returns a percent sales of the region by total sales in that country. Region input is accepted only by city. Districts are not accepted. If city name is not found, exception is thrown.         Parameters:              product (str) : Product name             sales (int) : Sales Volume         Returns:              percent_sales (float): Percent of total sales of                                        product."""

2. 让代码的逻辑更加直观易读

 

不推荐:

  •  
if is_white == Falseif not is_white == False

推荐:

  •  
is_white = Trueif is_white:else:

3. 使用“.join”代替“+”实现字符串连接

 

不推荐:

  •  
my_name = ‘firstname’+ ‘ ‘ + ‘lastname’

推荐:

  •  
my_name = " ".join(['firstname','lastname'])

4. 使用List代替for循环读取数组

  •  
numbers = [1,2,3,4,5,6,7,8,9,10]

不推荐:

  •  
even_halves = [ ]for num in numbers:    if num%2 == 0:       even_halves.append(num/2)print(even_halves)

推荐:

  •  
even_halves = [num/2 for num in numbers if num%2==0]

5. 使用def函数代替lambda给变量赋值

 

不推荐:

  •  
squared = lamdba x: x**2

推荐:

  •  
def squared(x):   return x**2

6. 不要把代码都挤在一行

 

注意文本换行!

 

不推荐:

  •  
df = pd.read_excel('This/extremely/long/file/path/that/extends/ /to/the/next/line/and/screws/with/indentation.xlsx')mylist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20000,30000,3100000320000]

推荐:

  •  
filepath = "this/sweet/line/" \           "continued/prettily/"\           "looksbetter.xlsx"df = pd.read_excel(filepath)my_list = [1,2,3,4,5,6,7,8,9,10,11,          12,13,14,15,16,17,18,19,          20000,30000,3100000,320000]if this_happens or that_happens \   or these_happen:      print('blah')else:   print('the other blah')

7. 多用range,少用List

 

不推荐:

  •  
indices = [0,2,4,6,8,10]for idX in indices:    print(name[idX])

推荐:

  •  
for idX in range(0,12,2):    print(name[idX])

8. 在“try”模块下保留最精简的代码

 

不推荐:

  •  
try:   names = get_data(students, classroom)   numbers = get_scores(students, classroom)   return names,numbersexcept KeyError:

推荐:

  •  
try:    names = get_data(students, classroom)    numbers = get_scores(students, classroom)except KeyError:    print('That's not a student in this classroom!')return names, numbers

9. 更多地使用set

 

如果在当前情况下不需要大量功能,则最好使用集合而不是其他数据结构。

  •  
data = {‘find_this’, ‘among’, ‘all_the’,'other',’data’}if‘find_this’ in data:   print(‘this exists!’)long_stuff = [‘this’,’list’,’list’,’is’,             ’enormous’,’oh’,’my’,’god’,             ’god’,’what’,’is’,             ’unique’,’unique’]unique_values = set(long_stuff)

10. 使用zip迭代多个列表

  •  
students = [‘tom’,’dick’,’harry’,’larry’,’tim’,’benny’]scores = [100,20,40,60,30,40]

不推荐:

  •  
for i in range(len(students)):    print(student[i],scores[i]

推荐:

  •  
for student,score in zip(students,scores):    print(student,score)

这就是一些使用python的小技巧。遵循良好的编程风格,做一个优秀的程序员!

 

·  END  ·

10个简洁的Python编码技巧_10个简洁的Python编码技巧_02