温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Pythonic的使用方法有哪些

发布时间:2021-10-26 09:23:34 来源:亿速云 阅读:119 作者:iii 栏目:web开发

这篇文章主要讲解了“Pythonic的使用方法有哪些”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Pythonic的使用方法有哪些”吧!

1. 变量交换

交换两个变量的值,正常都会想利用一个中间临时变量来过渡。

tmp = a a = b b = tmp

能用一行代码解决的(并且不影响可读性的),决不用三行代码。

a,bb = b,a

2. 列表推导

下面是一个非常简单的 for 循环。

my_list = [] for i in range(10):     my_list.append(i*2)

在一个 for 循环中,如果逻辑比较简单,不如试用一下列表的列表推导式,虽然只有一行代码,但也逻辑清晰。

my_list = [i*2 for i in range(10)]

3. 单行表达式

上面两个案例,都将多行代码用另一种方式写成了一行代码。

这并不意味着,代码行数越少,就越 Pythonic 。

比如下面这样写,就不推荐。

print('hello'); print('world')  if x == 1: print('hello,world')  if <complex comparison> and <other complex comparison>:     # do something

建议还是按照如下的写法来

print('hello') print('world')  if x == 1:     print('hello,world')  cond1 = <complex comparison> cond2 = <other complex comparison> if cond1 and cond2:     # do something

4. 带索引遍历

使用 for 循环时,如何取得对应的索引,初学者习惯使用 range + len 函数

for i in range(len(my_list)):     print(i, "-->", my_list[i])

更好的做法是利用 enumerate 这个内置函数

for i,item in enumerate(my_list):     print(i, "-->",item)

5. 序列解包

使用 * 可以对一个列表解包

a, *rest = [1, 2, 3] # a = 1, rest = [2, 3]  a, *middle, c = [1, 2, 3, 4] # a = 1, middle = [2, 3], c = 4

6. 字符串拼接

如果一个列表(或者可迭代对象)中的所有元素都是字符串对象,想要将他们连接起来,通常做法是

letters = ['s', 'p', 'a', 'm'] s="" for let in letters:     s += let

更推荐的做法是使用 join 函数

letters = ['s', 'p', 'a', 'm'] word = ''.join(letters)

7. 真假判断

判断一个变量是否为真(假),新手习惯直接使用 == 与 True、False、None 进行对比

if attr == True:     print('True!')  if attr == None:     print('attr is None!')

实际上,""、[]、{} 这些没有任何元素的容器都是假值,可直接使用 if not xx 来判断。

if attr:     print('attr is truthy!')  if not attr:     print('attr is falsey!')

8. 访问字典元素

当直接使用 [] 来访问字典里的元素时,若key不存在,是会抛异常的,所以新会可能会先判断一下是否有这个 key,有再取之。

d = {'hello': 'world'} if d.has_key('hello'):     print(d['hello'])    # prints 'world' else:     print('default_value')

更推荐的做法是使用 get 来取,如果没有该 key 会默认返回 None(当然你也可以设置默认返回值)

d = {'hello': 'world'}  print(d.get('hello', 'default_value')) # prints 'world' print(d.get('thingy', 'default_value')) # prints 'default_value'

9. 操作列表

下面这段代码,会根据条件过滤过列表中的元素

a = [3, 4, 5] b = [] for i in a:     if i > 4:         b.append(i)

实际上可以使用列表推导或者高阶函数 filter 来实现

a = [3, 4, 5] b = [i for i in a if i > 4] # Or: b = filter(lambda x: x > 4, a)

除了 filter 之外,还有 map、reduce 这两个函数也很好用

a = [3, 4, 5] b = map(lambda i: i + 3, a) # b: [6,7,8]

10. 文件读取

文件读取是非常常用的操作,在使用完句柄后,是需要手动调用 close 函数来关闭句柄的

fp = open('file.txt') print(fp.read()) fp.close()

如果代码写得太长,即使你知道需要手动关闭句柄,却也会经常会漏掉。因此推荐养成习惯使用 with open  来读写文件,上下文管理器会自动执行关闭句柄的操作

with open('file.txt') as fp:     for line in fp.readlines():         print(line)

11. 代码续行

将一个长度较长的字符串放在一行中,是很影响代码可读性的(下面代码可向左滑动)

long_string = 'For a long time I used to go to bed early. Sometimes, when I had put out my candle, my eyes would close so quickly that I had not even time to say “I&rsquo;m going to sleep.”'

稍等注重代码可读性的人,会使用三个引号 \来续写

long_string = 'For a long time I used to go to bed early. ' \               'Sometimes, when I had put out my candle, ' \               'my eyes would close so quickly that I had not even time to say “I&rsquo;m going to sleep.”'

不过,对我来说,我更喜欢这样子写 使用括号包裹 ()

long_string = (     "For a long time I used to go to bed early. Sometimes, "     "when I had put out my candle, my eyes would close so quickly "     "that I had not even time to say “I&rsquo;m going to sleep.”" )

导包的时候亦是如此

from some.deep.module.inside.a.module import (     a_nice_function, another_nice_function, yet_another_nice_function)

12. 显式代码

有时候出于需要,我们会使用一些特殊的魔法来使代码适应更多的场景不确定性。

def make_complex(*args):     x, y = args     return dict(**locals())

但若非必要,请不要那么做。无端增加代码的不确定性,会让原先本就动态的语言写出更加动态的代码。

def make_complex(x, y):     return {'x': x, 'y': y}

13. 使用占位符

对于暂不需要,却又不得不接收的的变量,请使用占位符

filename = 'foobar.txt' basename, _, ext = filename.rpartition('.')

14. 链式比较

对于下面这种写法

score = 85 if score > 80 and score < 90:     print("良好")

其实还有更好的写法

score = 85 if 80 < score < 90:     print("良好")

如果你理解了上面的链式比较操作,那么你应该知道为什么下面这行代码输出的结果是 False

>>> False == False == True  False

15. 三目运算

对于简单的判断并赋值

age = 20 if age > 18:     type = "adult" else:     type = "teenager"

其实是可以使用三目运算,一行搞定。

age = 20   b = "adult" if age > 18 else "teenager"

感谢各位的阅读,以上就是“Pythonic的使用方法有哪些”的内容了,经过本文的学习后,相信大家对Pythonic的使用方法有哪些这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI