更多课程 选择中心


Python培训

400-111-8989

Python 的这些特性,很多老司机都不知道


import this

先来个彩蛋,import this 是Python里面的一个彩蛋,把 this 模块导入进来就有一个Python开发哲学19条,写代码都应该遵循这些规则。

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

交换两个变量

在其它语言中,两个变量的值互换需要引入一个临时变量

temp = a
a = b
b = temp

在 Python 一行代码可以实现变量互换,是不是很神奇

b, a = a, b

检查真假值

判断一个列表是否为空,在其它语言中就是检查它的长度是否为零,如果为零就是空列表

>>> if len(items) != 0:
...     pass

在Python中,有更优雅的处理方式,直接使用:

>>> if items:
...     pass

获取列表元素的下标索引

Python中迭代列表比较特殊,不需要下标索引来定位里面的元素,而知直接进行迭代,迭代出来的就是每个元素本身。

>>> for item in items:
...     print(item)
...
zero
one
two
three

如果我想知道 one 是第几个元素,如何获取每个元素的下标索引呢?可以这样:

>>> for i in range(len(items)):
...     print(i, '---', items[i])
... 0 --- zero 1 --- one 2 --- two 3 --- three

其实还有更便利的方式获取下标元素,就是使用 enumerate 函数

>>> for i, item in enumerate(items):
...     print(i, '---', item)
... 0 --- zero 1 --- one 2 --- two 3 --- three

用列表推导式代替 map、filter 函数

map 是 Python 函数式编程的主要方法,比如可以使用map实现对列表的操作,例如我要把列表中的每个元素*2

>>> nums = [1,2,3,4,5]
>>> list(map(lambda i: i*2, nums))
[2, 4, 6, 8, 10]

用map还要使用晦涩难懂的匿名函数,而用列表推导式速度快,又直观

>>> [i*2 for i in nums]
[2, 4, 6, 8, 10]

巧用 for … else

来看这样的场景,就是你要在某个列表中搜索是否存在某个值,如果找到了就不在继续查找,如果没有到继续往后找,直到最后没找到位置,不管有没有找到都要告诉我,我们可以用一个标记变量来标识有没有找到。

found = False for i in foo:
    if i == 0:
        found = True        break if not found: 
    print("i was never 0")

这种场景就特别适合用 for … else 语法来实现

for i in foo:
    if i == 0:
        break else:
    print("i was never 0")

用 type 动态的创建类

我们都知道用 class 关键字定义一个类

>>> class Foo:
...     x = "foo" ...
>>> Foo.x 'foo'

其实还有另外一种方法创建类,就是使用 type 函数

>>> Foo = type("Foo",(), {"x":"foo"})
>>> Foo
<class '__main__.Foo'>
>>> Foo.x
'foo'

预约申请免费试听课

填写下面表单即可预约申请免费试听! 怕学不会?助教全程陪读,随时解惑!担心就业?一地学习,可全国推荐就业!

上一篇:Python|字符串的简单运算
下一篇:Python 网络编程基础入门

2021年Python全套免费视频教程在哪里?

Python编程学习路线

Python最高有几级?

人工智能与语音遥控的区别?

  • 扫码领取资料

    回复关键字:视频资料

    免费领取 达内课程视频学习资料

Copyright © 2023 Tedu.cn All Rights Reserved 京ICP备08000853号-56 京公网安备 11010802029508号 达内时代科技集团有限公司 版权所有

选择城市和中心
黑龙江省

吉林省

河北省

湖南省

贵州省

云南省

广西省

海南省