Python经常使用的8个高级函数

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

https://space.bilibili.com/523606542

lambda

它们在其余语言中也被称为匿名函数。若是你不想在程序中对一个函数使用两次,你也许会想用lambda表达式,它们和普通的函数彻底同样。函数

lambda argument: manipulate(argument)网站

lambda 参数:操做(参数)spa

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 中返回一个新的排序列表。3d

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

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

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

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

三元表达式

三元运算符一般在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( iterable, start=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

相关文章
相关标签/搜索