0
点赞
收藏
分享

微信扫一扫

Python常用的8个高级函数


Python爬虫、数据分析、网站开发等案例教程视频免费在线观看

https://space.bilibili.com/523606542


lambda

它们在其他语言中也被称为匿名函数。如果你不想在程序中对一个函数使用两次,你也许会想用lambda表达式,它们和普通的函数完全一样。

lambda argument: manipulate(argument)

lambda 参数:操作(参数)

add = lambda x, y: x + y

print(add(3, 5))
# Output: 8
a = [(1, 2), (4, 1), (9, 10), (13, -3)]

def f(x):
return x[1]

# a.sort(key=f)
a.sort(key=lambda x: x[1])

print(a)
# Output: [(13, -3), (4, 1), (1, 2), (9, 10)]

sorted

sorted(iterable, *, key=None, reverse=False)

从 iterable 中的 item 中返回一个新的排序列表。

有两个可选参数,必须将其指定为关键字参数。

key 指定一个带有一个参数的函数,用于从每个列表元素中提取比较键:key=str.lower。默认值是 None(直接比较元素)。

reverse 是一个布尔值。如果设置为 True,那么列表元素按照每个比较被颠倒的顺序进行排序。

内置的 sorted() 函数排序是稳定的。如果确保不会更改比较相等的元素的相对顺序,则排序是稳定的 。

三元表达式

三元运算符通常在Python里被称为条件表达式,这些表达式基于真(true)/假(false)的条件判断.

它允许用简单的一行快速判断,而不是使用复杂的多行if语句。 这在大多数时候非常有用,而且可以使代码简单可维护。

# 如果条件为真,返回真 否则返回假
condition_is_true if condition else condition_is_false
if condition:
result = condition_is_true
else:
result = condition_is_false

map

map(function, iterable, ...)

返回一个将 function 应用于每个 iterable item 的迭代器,从而产生结果。如果传递额外的 iterable 参数,function 必须采用多个参数并应用于并行所有迭代中的项目。使用多个迭代器时,当最短迭代器耗尽时,迭代器停止。

In [54]: list1 = [1, 2, 3, 4, 5, 6]

In [55]: list2 = [4, 3, 7, 1, 9]

In [56]: list(map(str, list1))
Out[56]: ['1', '2', '3', '4', '5', '6']

In [57]: list(map(lambda x, y: x+y, list1, list2))
Out[57]: [5, 5, 10, 5, 14]

enumerate

enumerate( iterablestart=0)

返回一个枚举对象。 iterable 必须是一个序列,一个迭代器或其他支持迭代的对象。由 enumerate() 返回的迭代器的 __next__() 方法返回一个元组,该元组包含一个计数(从 start 开始,默认值为 0)以及遍历迭代获得的值。

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

zip

zip(*iterables)

制作一个迭代器,用于聚合来自每个迭代器的元素。

返回元组的迭代器,其中第 i 个元组包含来自每个参数序列或迭代的第 i 个元素。当最短的输入迭代耗尽时,迭代器停止。使用单个迭代参数,它将返回 1 元组的迭代器。没有参数,它返回一个空的迭代器。

与 * 操作符一起使用 zip() 可用于解压缩列表:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
data = zip(list1, list2)
data = sorted(data)
list1, list2 = map(lambda t: list(t), zip(*data))

filter

filter(function, iterable)

用那些 function 返回 true 的 iterable 元素构造一个迭代器。iterable 可以是序列,支持迭代的容器或迭代器。如果 function 为 None,则假定标识函数为 false,即为 false 的所有元素都被删除。

# 过滤0-10之间的偶数
In [8]: list(filter(lambda x: x%2==0, range(10)))
Out[8]: [0, 2, 4, 6, 8]

reduce

reduce函数的用法和map很类似,也是一个函数f和一个list,但是函数的入口参数一定要是两个,reduce也是对每个元素进行反复调用,最后返回最终的值,而map是返回一个list

python3里面reduce已经从全局函数里面移除了,需要用的话要 from functools import reduce


举报

相关推荐

0 条评论