Python 进阶必须了解的 7 个 tips

Python 进阶必须了解的 7 个 tips

原创 waylons 大头兵程序员 2024-02-20 08:03 广东

大头兵程序员程序员的学习分享和工具推荐,高效学习,快乐生活
40篇原创内容

公众号背景
Python 作为一门流行的语言,因为语法简单上手容易广受青睐。但是,如果是初学者或者是先学习了其他语言同学,很容易写出不符合 Python 风格(Pythonic)的代码,或者掉入一些潜在的陷阱中。
本文将从 Pythonic 代码和常见的 Python 陷阱两个方面,介绍 Python 进阶必须了解的 7 个 tips。
Pythonic 代码
所谓 Pythonic,其实就是 Python 风格的代码,不这么写不会有语法问题,但是会让读代码的人认为代码写得不地道。
所以,写出 Pythonic 代码是 Python 进阶的必经之路。
用 enumerate 代替 range
如果先学其他语言再学 Python,很容易写出这样的循环代码:

animals = ['cat', 'dog', 'moose']
for i in range(len(animals)): 
 print(i, animals[i])

Python 提供了默认函数让我们更好地实现:

animals = ['cat', 'dog', 'moose']
for i, animal in enumerate(animals): 
 print(i, animal)

用 with 打开关闭文件
按照读取文件的顺序,我们打开一个文件的方式:

fileObj = open('spam.txt', 'w')
fileObj.write('Hello, world!')
fileObj.close()

Pythonic 的方式是:

with open('spam.txt', 'w') as fileObj:
    fileObj.write('Hello, world!')

用 is 而非 == 判断 None

class SomeClass: 
 def __eq__(self, other):
  if other is None: 
   return True 
spam = SomeClass()
print(spam == None) # True 
print(spam is None) # False, pythonic 写法

Pythonic 字典操作
对于下标取值,可以通过 get 来保证取值不报错且有默认值。

d = {"a": "b"}
print(d["c"]) # not pythonic, raise error
print(d.get("c", None)) # pythonic, print(None)

当我们的字典需要对 key 进行统计的时候,非 pythonic 的写法是每次统计之前先判断是否存在 key:

numberOfPets = {'dogs': 2}
if 'cats' not in numberOfPets:
 numberOfPets['cats'] = 0
numberOfPets['cats'] += 10

pythonic 的写法是用 setdefault 函数:

numberOfPets = {'dogs': 2}
if 'cats' not in numberOfPets:
 numberOfPets['cats'] = 0
numberOfPets['cats'] += 10

常见的 Python 陷阱
在循环中添加或者删除 list 元素

greetings = ['hello', 'hello', 'mello', 'yello', 'hello']
for i, word in enumerate(greetings):
 if word != 'hello':
  del greetings[i]
print(greetings) # ['hello', 'hello', 'yello', 'hello']

因为 i 和 list 同时在变化,所以其实很难获得预期的结果:![[Pasted image 20240215234406.png]] 正确的写法应该是:

greetings = ['hello', 'hello', 'mello', 'yello', 'hello']
greetings = [word for word in greetings if word == 'hello']
print(greetings) # ['hello', 'hello', 'hello']

Python 赋值的是引用,而非复制值

a = [1,2,3]
b = a
a[1] = 3
print(b[1]) # 3
print(id(a) == id(b)) # True

这个是需要特别注意的,而且在可变对象传参的时候也是一样的,在函数中的修改函数之外也会生效。
别用可变对象作为函数参数默认值

def addIngredient(ingredient, sandwich=['bread', 'bread']):
 sandwich.insert(1, ingredient)
 return sandwich
mySandwich = addIngredient('avocado')
print(mySandwich) # ['bread', 'avocado', 'bread']
anotherSandwich = addIngredient('lettuce')
print(anotherSandwich) # ['bread', 'lettuce', 'avocado', 'bread']

可以看到,因为是可变对象,所以当默认参数在函数中有修改操作的时候,这些操作的影响会累加。因此,正确的做法应该是:

def addIngredient(ingredient, sandwich=None):
 if sandwich is None:
  sandwich = ['bread', 'bread']
 sandwich.insert(1, ingredient)
 return sandwich

以上就是“Python 进阶必须了解的 7 个 tips”的全部内容,希望对你有所帮助。

关于Python技术储备

学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!

一、Python所有方向的学习路线

Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

在这里插入图片描述

二、Python必备开发工具

img

三、Python视频合集

观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。

img

四、实战案例

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

img

五、Python练习题

检查学习结果。

img

六、面试资料

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

img

最后祝大家天天进步!!

上面这份完整版的Python全套学习资料已经上传至CSDN官方,朋友如果需要可以直接微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值