38

5 个越早知道越好的 Python 特性

 4 years ago
source link: https://www.leiphone.com/news/201912/rti9kv9W5nhuQXCH.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

iqaMz2y.png!web

Kirill Sharkovski 发布在 Unsplash 杂志上的照片

雷锋网AI开发者按,Python 是近十年来兴起的编程语言,并且被证明是一种非常强大的语言。我用 Python 构建了很多应用程序,从交互式地图到区块链。Python 有很多特性,初学者很难一开始就掌握所有的特性。

即使你是一个从其他语言(如 C 或 MATLAB)转换过来的程序员,用更高抽象级别的 Python 编写代码绝对是另一种体验。回顾起来,有很多 Python 特性如果我能早点知道,肯定能少走不少弯路。现在我想要重点介绍其中五个最重要的特性。

1.理解 List——压缩代码

很多人会将 lambda、map 和 filter 作为 Python 的「技巧」,每个初学者都应该学习这些技巧。虽然我相信它们是我们应该掌握的特性,但我发现由于缺乏灵活性,它们在大多数时候并不特别有用。

Lambda 是一种在一行中组合函数以供一次性使用的方法。如果函数被多次调用,性能将受到影响。另一方面,map 将函数应用于列表中的所有元素,而 filter 将获取满足用户定义条件的集合中元素的子集。

add_func = lambda z: z ** 2     
is_odd = lambda z: z%2 == 1    
multiply = lambda x,y: x*y     
 
aList = list(range(10))    
print(aList)    
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]     

2mYR7zB.png!web

Anastase Maragos 发表在 Unsplash 杂志上的照片

列表理解是一种简洁而灵活的方法,可以使用灵活的表达式和条件从其他列表创建列表。它是由方括号构造的,它有一个表达式或一个函数,只有当元素满足某个条件时,该表达式或函数才应用于列表中的每个元素。它还可以嵌套来处理嵌套列表,并且比使用 map 和 filter 灵活得多。

# Syntax of list comprehension [ expression(x) for x in aList if optional_condition(x) ] 
print(list(map(add_func, aList)))    
print([x ** 2 for x in aList])    
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]    
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]    
 
print(list(filter(is_odd, aList)))    
print([x for x in aList if x%2 == 1])    
# [1, 3, 5, 7, 9]    
# [1, 3, 5, 7, 9]    

2.列表循环

Python 允许使用负索引,其中 Altruts [-1]== Altrue[LeN(Listor)-1 ]。因此,我们可以通过调用 a list[-2] 等获得列表中的倒数第二个元素。

我们还可以使用语法 aList[start:end:step] 对列表进行切片,其中包含起始元素,但不包含结束元素。因此,aList[2:5] 的结果是 [2,3,4]。我们也可以通过调用 a list[::-1] 来反转列表,我发现这种技术非常优雅。

am2QBbM.png!web

Martin Shreder 发表在 Unsplash 杂志上的照片

列表也可以分解成单独的元素,或者使用星号将元素和子列表混合。

a, b, c, d = aList[0:4]    
print(f'a = {a}, b = {b}, c = {c}, d = {d}')    
# a = 0, b = 1, c = 2, d = 3     
 
 
a, *b, c, d = aList    
print(f'a = {a}, b = {b}, c = {c}, d = {d}')    
# a = 0, b = [1, 2, 3, 4, 5, 6, 7], c = 8, d = 9    

3.压缩和枚举:for 循环

Zip 函数创建一个迭代器,该迭代器聚合来自多个列表的元素。它允许在 for 循环中并行遍历列表并并行排序。它可以用星号来解压缩。

numList = [0, 1, 2]    
engList = ['zero', 'one', 'two']    
espList = ['cero', 'uno', 'dos']    
print(list(zip(numList, engList, espList)))    
# [(0, 'zero', 'cero'), (1, 'one', 'uno'), (2, 'two', 'dos')]     
 
 
for num, eng, esp in zip(numList, engList, espList):    
print(f'{num} is {eng} in English and {esp} in Spanish.')    
# 0 is zero in English and cero in Spanish.    
# 1 is one in English and uno in Spanish.    
# 2 is two in English and dos in Spanish.    
Eng = list(zip(engList, espList, numList))    
Eng.sort() # sort by engList    
a, b, c = zip(*Eng)     
 
 
print(a)    
print(b)    
print(c)    
# ('one', 'two', 'zero')    
# ('uno', 'dos', 'cero')    
# (1, 2, 0)    

nmiq6j2.png!web

Erol Ahmed 发表在 Unsplash 杂志上的照片

枚举一开始可能看起来有点吓人,但在许多情况下它是非常方便的。它是一个经常在 for 循环中使用的自动计数器,不需要在 for 循环中创建和初始化计数器变量 by counter=0 和 counter+=1。枚举和 zip 是构造 for 循环时最强大的两个工具。

upperCase = ['A', 'B', 'C', 'D', 'E', 'F']    
lowerCase = ['a', 'b', 'c', 'd', 'e', 'f']    
for i, (upper, lower) in enumerate(zip(upperCase, lowerCase), 1):    
        print(f'{i}: {upper} and {lower}.')    
# 1: A and a.    
# 2: B and b.    
# 3: C and c.    
# 4: D and d.    
# 5: E and e.    
# 6: F and f.    

4.生成器:内存效率

当我们打算对大量数据进行计算,但希望避免同时分配所有结果所需的内存时,会使用生成器。换句话说,它们会动态生成值,而不会将以前的值存储在内存中,因此我们只能对它们进行一次迭代。

它们通常用于读取大文件或使用关键字 yield 生成无限序列。我经常发现它在我的大多数数据科学项目中很有用。

def gen(n):    # an infinite sequence generator that generates integers >= n    
        while True:    
              yield n    
              n += 1     
 
 
G = gen(3)     # starts at 3    
print(next(G)) # 3    
print(next(G)) # 4    
print(next(G)) # 5    
print(next(G)) # 6    

5.虚拟环境:isolation

如果你读完本文中只记得其中一条,那么应该是虚拟环境的使用。

iM3UBnU.png!web

Matthew Kwong 发布在 Unsplash 上的照片

Python 应用程序通常使用很多不同的包,这些包来不同的开发人员,具有复杂的依赖关系。不同的应用程序是使用特定的库设置开发的,其中的结果不能使用其他库版本复制。不存在一次安装就满足所有应用要求的情况。

conda create -n venv pip python=3.7  # select python version source activate venv ... source deactivate 

因此,为每个应用程序创建独立的独立虚拟环境 venv 是非常重要的,这可以使用 pip 或 conda 来完成。

参考文章:

Visualizing Bike Mobility in London using Interactive Maps and Animations

via: https://towardsdatascience.com/5-python-features-i-wish-i-had-known-earlier-bc16e4a13bf4

雷锋网雷锋网雷锋网 (公众号:雷锋网)

雷锋网版权文章,未经授权禁止转载。详情见 转载须知

b6Zvmyn.png!web


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK