Python 多好用不用多说,大家看看自己用的语言就知道了。但是 Python 隐藏的高级功能你都 get 了吗?本文中,列举了 Python 中五种略高级的特征以及它们的使用方法,快来一探究竟吧!
<tt-image data-tteditor-tag="tteditorTag" contenteditable="false" class="syl1559286029549" data-render-status="finished" data-syl-blot="image" style="box-sizing: border-box; cursor: text; color: rgb(34, 34, 34); font-family: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "WenQuanYi Micro Hei", "Helvetica Neue", Arial, sans-serif; font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial; display: block;"><input class="pgc-img-caption-ipt" placeholder="图片描述(最多50字)" value="" style="box-sizing: border-box; outline: 0px; color: rgb(102, 102, 102); position: absolute; left: 187.5px; transform: translateX(-50%); padding: 6px 7px; max-width: 100%; width: 375px; text-align: center; cursor: text; font-size: 12px; line-height: 1.5; background-color: rgb(255, 255, 255); background-image: none; border: 0px solid rgb(217, 217, 217); border-radius: 4px; transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1) 0s;"></tt-image>
Python学习交流群:1004391443,这里有资源共享,技术解答,还有小编从最基础的Python资料到项目实战的学习资料都有整理,希望能帮助你更了解python,学习python
Python 是一种美丽的语言,它简单易用却非常强大。但你真的会用 Python 的所有功能吗?
任何编程语言的高级特征通常都是通过大量的使用经验才发现的。比如你在编写一个复杂的项目,并在 stackoverflow 上寻找某个问题的答案。然后你突然发现了一个非常优雅的解决方案,它使用了你从不知道的 Python 功能!
这种学习方式太有趣了:通过探索,偶然发现什么。这里推荐一下我们的Python学习扣qun:784,758,214,这里是python学习者聚集地
<pre spellcheck="false" style="box-sizing: border-box; margin: 5px 0px; padding: 5px 10px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-weight: 400; font-stretch: inherit; font-size: 16px; line-height: inherit; font-family: inherit; vertical-align: baseline; cursor: text; counter-reset: list-1 0 list-2 0 list-3 0 list-4 0 list-5 0 list-6 0 list-7 0 list-8 0 list-9 0; background-color: rgb(240, 240, 240); border-radius: 3px; white-space: pre-wrap; color: rgb(34, 34, 34); letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">下面是 Python 的 5 种高级特征,以及它们的用法。
Lambda 函数
Lambda 函数是一种比较小的匿名函数——匿名是指它实际上没有函数名。
Python 函数通常使用 def a_function_name() 样式来定义,但对于 lambda 函数,我们根本没为它命名。这是因为 lambda 函数的功能是执行某种简单的表达式或运算,而无需完全定义函数。
lambda 函数可以使用任意数量的参数,但表达式只能有一个。
</pre>
- x = lambda a, b : a * b
- print(x(5, 6)) # prints '30'
- x = lambda a : a*3 + 3
- print(x(3)) # prints '12'
<pre spellcheck="false" style="box-sizing: border-box; margin: 5px 0px; padding: 5px 10px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-weight: 400; font-stretch: inherit; font-size: 16px; line-height: inherit; font-family: inherit; vertical-align: baseline; cursor: text; counter-reset: list-1 0 list-2 0 list-3 0 list-4 0 list-5 0 list-6 0 list-7 0 list-8 0 list-9 0; background-color: rgb(240, 240, 240); border-radius: 3px; white-space: pre-wrap; color: rgb(34, 34, 34); letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">看它多么简单!我们执行了一些简单的数学运算,而无需定义整个函数。这是 Python 的众多特征之一,这些特征使它成为一种干净、简单的编程语言。
Map 函数
Map() 是一种内置的 Python 函数,它可以将函数应用于各种数据结构中的元素,如列表或字典。对于这种运算来说,这是一种非常干净而且可读的执行方式。
</pre>
- def square_it_func(a):
- return a * a
- x = map(square_it_func, [1, 4, 7])
- print(x) # prints '[1, 16, 47]'
- def multiplier_func(a, b):
- return a * b
- x = map(multiplier_func, [1, 4, 7], [2, 5, 8])
- print(x) # prints '[2, 20, 56]'看看上面的示例!我们可以将函数应用于单个或多个列表。实际上,你可以使用任何 Python 函数作为 map 函数的输入,只要它与你正在操作的序列元素是兼容的。
<pre spellcheck="false" style="box-sizing: border-box; margin: 5px 0px; padding: 5px 10px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-weight: 400; font-stretch: inherit; font-size: 16px; line-height: inherit; font-family: inherit; vertical-align: baseline; cursor: text; counter-reset: list-1 0 list-2 0 list-3 0 list-4 0 list-5 0 list-6 0 list-7 0 list-8 0 list-9 0; background-color: rgb(240, 240, 240); border-radius: 3px; white-space: pre-wrap; color: rgb(34, 34, 34); letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">Filter 函数
filter 内置函数与 map 函数非常相似,它也将函数应用于序列结构(列表、元组、字典)。二者的关键区别在于 filter() 将只返回应用函数返回 True 的元素。
详情请看如下示例:
</pre>
-
Our numbers
-
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
-
Function that filters out all numbers which are odd
-
def filter_odd_numbers(num):
-
if num % 2 == 0:
-
return True
-
else:
-
return False
-
filtered_numbers = filter(filter_odd_numbers, numbers)
-
print(filtered_numbers)
-
filtered_numbers = [2, 4, 6, 8, 10, 12, 14]
<pre spellcheck="false" style="box-sizing: border-box; margin: 5px 0px; padding: 5px 10px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-weight: 400; font-stretch: inherit; font-size: 16px; line-height: inherit; font-family: inherit; vertical-align: baseline; cursor: text; counter-reset: list-1 0 list-2 0 list-3 0 list-4 0 list-5 0 list-6 0 list-7 0 list-8 0 list-9 0; background-color: rgb(240, 240, 240); border-radius: 3px; white-space: pre-wrap; color: rgb(34, 34, 34); letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">我们不仅评估了每个列表元素的 True 或 False,filter() 函数还确保只返回匹配为 True 的元素。非常便于处理检查表达式和构建返回列表这两步。
Itertools 模块
Python 的 Itertools 模块是处理迭代器的工具集合。迭代器是一种可以在 for 循环语句(包括列表、元组和字典)中使用的数据类型。
使用 Itertools 模块中的函数让你可以执行很多迭代器操作,这些操作通常需要多行函数和复杂的列表理解。关于 Itertools 的神奇之处,请看以下示例:
</pre>
-
from itertools import *
-
Easy joining of two lists into a list of tuples
-
for i in izip([1, 2, 3], ['a', 'b', 'c']):
-
print i
-
('a', 1)
-
('b', 2)
-
('c', 3)
-
The count() function returns an interator that
-
produces consecutive integers, forever. This
-
one is great for adding indices next to your list
-
elements for readability and convenience
-
for i in izip(count(1), ['Bob', 'Emily', 'Joe']):
-
print i
-
(1, 'Bob')
-
(2, 'Emily')
-
(3, 'Joe')
-
The dropwhile() function returns an iterator that returns
-
all the elements of the input which come after a certain
-
condition becomes false for the first time.
-
def check_for_drop(x):
-
print 'Checking: ', x
-
return (x > 5)
-
for i in dropwhile(should_drop, [2, 4, 6, 8, 10, 12]):
-
print 'Result: ', i
-
Checking: 2
-
Checking: 4
-
Result: 6
-
Result: 8
-
Result: 10
-
Result: 12
-
The groupby() function is great for retrieving bunches
-
of iterator elements which are the same or have similar
-
properties
-
a = sorted([1, 2, 1, 3, 2, 1, 2, 3, 4, 5])
-
for key, value in groupby(a):
-
print(key, value), end=' ')
-
(1, [1, 1, 1])
-
(2, [2, 2, 2])
-
(3, [3, 3])
-
(4, [4])
-
(5, [5])
<pre spellcheck="false" style="box-sizing: border-box; margin: 5px 0px; padding: 5px 10px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-weight: 400; font-stretch: inherit; font-size: 16px; line-height: inherit; font-family: inherit; vertical-align: baseline; cursor: text; counter-reset: list-1 0 list-2 0 list-3 0 list-4 0 list-5 0 list-6 0 list-7 0 list-8 0 list-9 0; background-color: rgb(240, 240, 240); border-radius: 3px; white-space: pre-wrap; color: rgb(34, 34, 34); letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">Generator 函数
Generator 函数是一个类似迭代器的函数,即它也可以用在 for 循环语句中。这大大简化了你的代码,而且相比简单的 for 循环,它节省了很多内存。
比如,我们想把 1 到 1000 的所有数字相加,以下代码块的第一部分向你展示了如何使用 for 循环来进行这一计算。
如果列表很小,比如 1000 行,计算所需的内存还行。但如果列表巨长,比如十亿浮点数,这样做就会出现问题了。使用这种 for 循环,内存中将出现大量列表,但不是每个人都有无限的 RAM 来存储这么多东西的。Python 中的 range() 函数也是这么干的,它在内存中构建列表。
代码中第二部分展示了使用 Python generator 函数对数字列表求和。generator 函数创建元素,并只在必要时将其存储在内存中,即一次一个。这意味着,如果你要创建十亿浮点数,你只能一次一个地把它们存储在内存中!Python 2.x 中的 xrange() 函数就是使用 generator 来构建列表。
上述例子说明:如果你想为一个很大的范围生成列表,那么就需要使用 generator 函数。如果你的内存有限,比如使用移动设备或边缘计算,使用这一方法尤其重要。
也就是说,如果你想对列表进行多次迭代,并且它足够小,可以放进内存,那最好使用 for 循环或 Python 2.x 中的 range 函数。因为 generator 函数和 xrange 函数将会在你每次访问它们时生成新的列表值,而 Python 2.x range 函数是静态的列表,而且整数已经置于内存中,以便快速访问。
</pre>
-
(1) Using a for loopv
-
numbers = list()
-
for i in range(1000):
-
numbers.append(i+1)
-
total = sum(numbers)
-
(2) Using a generator
-
def generate_numbers(n):
-
num, numbers = 1, []
-
while num < n:
-
numbers.append(num)
-
num += 1
-
return numbers
-
total = sum(generate_numbers(1000))
-
(3) range() vs xrange()
-
total = sum(range(1000 + 1))
-
total = sum(xrange(1000 + 1))
网友评论