map

map() 会根据提供的函数对指定可迭代序列做映射。

map(function, iterable, ...)

  • function -- 函数
  • iterable -- 一个或多个序列

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

返回值

  • Python 2.x 返回列表。
  • Python 3.x 返回迭代器。可以通过 list()转换为 list

python map() is an iterator, so that we can iterate over elements. it's return value can be converted to tuple ,lists map is also very usefull to use lambda functinons and it applies function to all items in the input list

map(function, iterable, ...) the argument iterable can be any object capable of returning its members one at a time not just lists. For example, map(lambda x:x*x, range(10)) yields an iterable of the first ten perfect squares.

lambda

A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one expression.

语法:lambda arguments : expression

The expression is executed and the result is returned:

  1. 通常是在需要一个不太复杂的函数,但是又不想费神去命名一个函数的场合下使用。

    1
    2
    3
    4
    def increcement(x):
    return x + 1

    increcement(2)

    1
    (lambda x: x + 1)(2)

    两个功能是一致的。但是明显可以看出对于一些简单的功能来说,写成 lamdba 匿名函数更具备可读性。

  2. lambda 函数也是表达式,也可以命名

    1
    2
    3
    4
    In [4]: addone = lambda x: x+1

    In [5]: addone(3)
    Out[5]: 4

  3. 多个参数 逗号分割,不用括号包围 lambda x, y: x+y

  4. 函数参数(高阶函数) A lambda function can be a higher-order function by taking a function (normal or lambda) as an argument

    1
    2
    3
    4
    high_ord_func = lambda x, func: x + func(x)
    high_ord_func(2, lambda x: x * x)

    high_ord_func(2, lambda x: x + 3)

    Python exposes higher-order functions as built-in functions or in the standard library. Examples include map(), filter(), functools.reduce(), as well as key functions like sort(), sorted(), min(), and max(). You’ll use lambda functions together with Python higher-order functions

使用

一般在 sorted, max、map 等函数里的 key 常用 lambda. 比如有一个比较复杂的数组结构,s = [('a', 3), ('b', 2), ('c', 1)]对这个数组用第二个元素排序。可以写成 sorted(s, key=lambda x:x[1])

先举一个普通的 Python 例子:将一个 list 里的每个元素都平方: map(lambda x: x*x, [y for y in range(10)])

这个写法要好过

1
2
3
def sq(x):
return x * x
map(sq, [y for y in range(10)])

因为后者多定义了一个(污染环境的)函数,尤其如果这个函数只会使用一次的话。而且第一种写法实际上更易读,因为那个映射到列表上的函数具体是要做什么,非常一目了然。如果你仔细观察自己的代码,会发现这种场景其实很常见:你在某处就真的只需要一个能做一件事情的函数而已,连它叫什么名字都无关紧要。Lambda 表达式就可以用来做这件事。

进一步讲,匿名函数本质上就是一个函数,它所抽象出来的东西是一组运算。这是什么意思呢?类比 a = [1, 2, 3]f = lambda x : x + 1

每当你需要这样写时,

1
2
3
4
a = [1, 2, 3]
r = []
for each in a:
r.append(each+1)

你会发现自己如果能将「遍历列表,给遇到的每个元素都做某种运算」的过程从一个循环里抽象出来成为一个函数 map,然后用 lambda 表达式将这种运算作为参数传给 map 的话,Python 之中,类似能用到 lambda 表达式的「高级」函数还有 reduce、filter 等等。这种能够接受一个函数作为参数的函数叫做「高阶函数」(higher-order function),是来自函数式编程(functional programming)的思想。

和其他很多语言相比,Python 的 lambda 限制多多,最严重的当属它只能由一条表达式组成。这个限制主要是为了防止滥用,因为当人们发觉 lambda 很方便,就比较容易滥用,可是用多了会让程序看起来不那么清晰,毕竟每个人对于抽象层级的忍耐 / 理解程度都有所不同。

意义

  1. 可以在表达式当中直接定义一个函数,而不需要将定义函数和表达式分开,这样有助于将逻辑用更紧凑的方式表达出来。它的
  2. 引入了闭包。基本上来说常见的支持 lambda 表达式的语言里,不存在不支持闭包的 lambda 表达式; 从函数式编程的角度来说,支持闭包也是很重要的。闭包是指将当前作用域中的变量通过值或者引用的方式封装到 lambda 表达式当中,成为表达式的一部分,它使你的 lambda 表达式从一个普通的函数变成了一个带隐藏参数的函数。
  3. 第三个意义(如果有的话)是允许函数作为一个对象来进行传递。某些语言由于历史原因,只有匿名函数可以作为对象传递,而具名函数不可以,比如 PHP。

Python 里嵌套定义的非 lambda、有名的函数一样引入了闭包以及可以任意传递,所以.对 Python 来说意义只有第一条,其实省名字和写到一行是次要的,重点在于嵌入到表达式里面

sorted 函数

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

iterable: 可迭代变量 key: 函数名,可以是内置函数,也可以是自己写的 reverse: 默认为 False,升序,如果想要逆序将其设置为 True。

返回排序后的列表,原可迭代对象不变。

示例:

1
2
3
4
5
6
7
8
def take_second(elem):
return elem[1]

# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]

# sort list with key
sorted_list = sorted(random, key=take_second)

sort

First, sort is a method of the list class and can only be used with lists. It is not a built-in with an iterable passed to it.

Second, .sort() returns None and modifies the values in place(直接对原列表进行修改). Let’s take a look at the impacts of both of these differences in code:

eval 函数

eval(expression[, globals[, locals]])

参数

  • expression -- 表达式。
  • globals -- 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
  • locals -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。

返回值

返回表达式计算结果。

eval() 函数十分强大ーー将字符串当成有效的表达式来求值并返回计算结果

The eval() method parses the expression passed to it and runs python expression(code) within the program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 基本的数学计算
In [2]: eval('1+2*2')
Out[2]: 5

# 字符串重复
In [8]: eval("'*'*20")
Out[8]: '********************'

# 字符串转换为列表
In [3]: li = eval('[1,2,3,4,5,9]')

In [4]: li
Out[4]: [1, 2, 3, 4, 5, 9]

#字符串转换为字典
In [6]: dic = eval("{'name':'xiaoming', 'age':10}")

In [7]: dic
Out[7]: {'name': 'xiaoming', 'age': 10}

注意使用 eval 时,字符串变量的函数名需要使用格式化字符串, 而直接写变量或者函数名是可以的。

1
2
3
4
a = {1,2,3}
content = {2,3,4,5}
operation = update()
eval(f"a.{operation}(content)")

字符串转换为字典

  1. eval 函数

    1
    2
    3
    4
    5
    6
    7
    In [1]: user = "{'name' : 'jim', 'sex' : 'male', 'age': 18}"

    In [2]: eval(user)
    Out[2]: {'name': 'jim', 'sex': 'male', 'age': 18}

    In [3]: type(eval(user))
    Out[3]: dict

  2. exec 函数

    1
    2
    3
    4
    In [4]: exec(f"user_dict={user}")

    In [5]: user_dict
    Out[5]: {'name': 'jim', 'sex': 'male', 'age': 18}

不要滥用 eval

在开发时,千万不要使用 eval 直接转换 input 的结果

1
__import__('os').system('ls')

等价代码

1
2
import os
os.system('终端命令')

执行成功,返回 0

执行失败,返回错误信息

eval in Python

eval alternative: function reference

见 Python variables and parameters feature 一文 以及 string-validators_forum

any 函数

Definition and Usage

The any() function returns True if any item in an iterable are true(元素除了是 0、空、FALSE 外都算 TRUE。), otherwise it returns False.

If the iterable object is empty, the any() function will return False.

Syntax

any(iterable)

Parameter Values

Parameter Description
iterable An iterable object (list, tuple, dictionary)

Note: When used on a dictionary, the any() function checks if any of the keys are true, not the values.

all 函数

The all() function returns True if all items in an iterable are true, otherwise it returns False.

If the iterable object is empty, the all() function also returns True.

补充:

语法糖(Syntactic sugar)是由英国计算机科学家彼得·兰丁发明的一个术语,指计算机语言中添加的某种语法,这种语法对语言的功能没有影响,但是更方便程序员使用。语法糖让程序更加简洁,有更高的可读性。 --wikipedia

参考推荐:

Lambda 表达式有何用处?如何使用? 什么时候使用 Lambda 函数? Python any() Function Python all() Function

How to Use Python Lambda Functions