常用内置函数

    Built-in Functions    
abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()  
delattr() hash() memoryview() set()  

abs/round/sum

>>> abs(1)
>>> abs(-1)         # 求绝对值
>>> round(1.234,2)
1.23
>>> round(1.269,2)  # 四舍五入
1.27
>>> sum([1,2,3,4])
>>> sum((1,3,5,7))  # 接收数字组成的元组/列表
>>> def func():pass  
>>> callable(func)   # 判断一个变量是否可以调用 函数可以被调用
True
>>> a = 123          # 数字类型a不能被调用
>>> callable(a)
False
>>> chr(97)          # 将一个数字转换成一个字母
'a'
>>> chr(65)
'A'
>>> dir(123)         # 查看数字类型中含有哪些方法
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> dir('abc')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

eval/exec

>>> eval('1+2-3*4/5')  # 执行字符串数据类型的代码并且将值返回
0.6000000000000001
>>> exec('print(123)') # 执行字符串数据类型的代码但没有返回值
123

enumerate

>>> enumerate(['apple','banana'],1)   # 会给列表中的每一个元素拼接一个序号
<enumerate object at 0x113753fc0>
>>> list(enumerate(['apple','banana'],1))
[(1, 'apple'), (2, 'banana')]

max/min

>>> max(1,2,3,)     # 求最小值
3
>>> min(2,1,3)      # 求最大值
1

sorted

将给定的可迭代对象进行排序,并生成一个有序的可迭代对象。

>>> sorted([1, 4, 5, 12, 45, 67])  # 排序,并生成一个新的有序列表
[1, 4, 5, 12, 45, 67]

还接受一个key参数和reverse参数。

>>> sorted([1, 4, 5, 12, 45, 67], reverse=True)
[67, 45, 12, 5, 4, 1]
list1 = [
    {'name': 'Zoe', 'age': 30},
    {'name': 'Bob', 'age': 18},
    {'name': 'Tom', 'age': 22},
    {'name': 'Jack', 'age': 40},
]

ret = sorted(list1, key=lambda x: x['age'])
print(ret)

# [{'name': 'Bob', 'age': 18}, {'name': 'Tom', 'age': 22}, {'name': 'Zoe', 'age': 30}, {'name': 'Jack', 'age': 40}]

zip

zip函数接收一个或多个可迭代对象作为参数,最后返回一个迭代器:

>>> x = ["a", "b", "c"]
>>> y = [1, 2, 3]
>>> a = list(zip(x, y))  # 合包
>>> a
[('a', 1), ('b', 2), ('c', 3)]
>>> b =list(zip(*a))  # 解包
>>> b
[('a', 'b', 'c'), (1, 2, 3)]

zip(x, y) 会生成一个可返回元组 (m, n) 的迭代器,其中m来自x,n来自y。 一旦其中某个序列迭代结束,迭代就宣告结束。 因此迭代长度跟参数中最短的那个序列长度一致。

>>> x = [1, 3, 5, 7, 9]
>>> y = [2, 4, 6, 8]
>>> for m, n in zip(x, y):
...   print(m, n)
... 
2
4
6
8

如果上面不是你想要的效果,那么你还可以使用 itertools.zip_longest() 函数来代替这个例子中的zip。

>>> from itertools import zip_longest
>>> x = [1, 3, 5, 7, 9]
>>> y = [2, 4, 6, 8]
>>> for m, n in zip_longest(x, y):
...   print(m, n)
... 
2
4
6
8
None

zip其他常见应用:

>>> keys = ["name", "age", "salary"]
>>> values = ["Andy", 18, 50]
>>> d = dict(zip(keys, values))
>>> d
{'name': 'Andy', 'age': 18, 'salary': 50}

map

map()接收两个参数func(函数)和seq(序列,例如list)。如下图:

常用内置函数、三元运算、递归

map()将函数func应用于序列seq中的所有元素。在Python3之前,map()返回一个列表,列表中的每个元素都是将列表或元组“seq”中的相应元素传入函数func返回的结果。Python 3中map()返回一个迭代器。

因为map()需要一个函数作为参数,所以可以搭配lambda表达式很方便的实现各种需求。

例子1:将一个列表里面的每个数字都加100:

>>> l = [11, 22, 33, 44, 55]
>>> list(map(lambda x:x+100, l))
[111, 122, 133, 144, 155]

例子2:

使用map就相当于使用了一个for循环,我们完全可以自己定义一个my_map函数:

def my_map(func, seq):
    result = []
    for i in seq:
        result.append(func(i))
    return result

测试一下我们自己的my_map函数:

>>> def my_map(func, seq):
...     result = []
...     for i in seq:
...         result.append(func(i))
...     return result
... 
>>> l = [11, 22, 33, 44, 55]
>>> list(my_map(lambda x:x+100, l))
[111, 122, 133, 144, 155]

我们自定义的my_map函数的效果和内置的map函数一样。

当然在Python3中,map函数返回的是一个迭代器,所以我们也需要让我们的my_map函数返回一个迭代器:

def my_map(func, seq):
    for i in seq:
        yield func(i)

测试一下:

>>> def my_map(func, seq):
...     for i in seq:
...         yield func(i)
... 
>>> l = [11, 22, 33, 44, 55]
>>> list(my_map(lambda x:x+100, l))
[111, 122, 133, 144, 155]

与我们自己定义的my_map函数相比,由于map是内置的因此它始终可用,并且始终以相同的方式工作。它也具有一些性能优势,通常会比手动编写的for循环更快。当然内置的map还有一些高级用法:

例如,可以给map函数传入多个序列参数,它将并行的序列作为不同参数传入函数:

拿pow(arg1, arg2)函数举例,

>>> pow(2, 10)
>>> pow(3, 11)
>>> pow(4, 12)
>>> list(map(pow, [2, 3, 4], [10, 11, 12]))
[1024, 177147, 16777216]

filter

filter函数和map函数一样也是接收两个参数func(函数)和seq(序列,如list),如下图:

常用内置函数、三元运算、递归

filter函数类似实现了一个过滤功能,它过滤序列中的所有元素,返回那些传入func后返回True的元素。也就是说filter函数的第一个参数func必须返回一个布尔值,即True或者False。

下面这个例子,是使用filter从一个列表中过滤出大于33的数:

>>> l = [30, 11, 77, 8, 25, 65, 4]
>>> list(filter(lambda x: x>33, l))
[77, 65]

利用filter()还可以用来判断两个列表的交集:

>>> x = [1, 2, 3, 5, 6]
>>> y = [2, 3, 4, 6, 7]
>>> list(filter(lambda a: a in y, x))
[2, 3, 6]

补充:reduce

reduce
注意:Python3中reduce移到了functools模块中,你可以用过from functools import reduce来使用它。

reduce同样是接收两个参数:func(函数)和seq(序列,如list),如下图:

 

常用内置函数、三元运算、递归

reduce最后返回的不是一个迭代器,它返回一个值。

reduce首先将序列中的前两个元素,传入func中,再将得到的结果和第三个元素一起传入func,…,这样一直计算到最后,得到一个值,把它作为reduce的结果返回。

原理类似于下图:

常用内置函数、三元运算、递归

 

看一下运行结果:

>>> from functools import reduce
>>> reduce(lambda x,y:x+y, [1, 2, 3, 4])
10

再来练习一下,使用reduce求1~100的和:

>>> from functools import reduce
>>> reduce(lambda x,y:x+y, range(1, 101))
5050

lambda

lambda是匿名函数,也就是没有名字的函数。lambda的语法非常简单:

常用内置函数、三元运算、递归

直白一点说:为了解决那些功能很简单的需求而设计的一句话函数

注意:

使用lambda表达式并不能提高代码的运行效率,它只能让你的代码看起来简洁一些。

#这段代码
def func(x, y):
    return x + y#换成匿名函数
lambda x, y:x+y

ambda表达式和定义一个普通函数的对比:

常用内置函数、三元运算、递归

 

我们可以将匿名函数赋值给一个变量然后像调用正常函数一样调用它。

匿名函数的调用和正常的调用也没有什么分别。 就是 函数名(参数) 就可以了~~~

练一练:

请把以下函数变成匿名函数
def func(x, y):
    return x + y

上面是匿名函数的函数用法。除此之外,匿名函数也不是浪得虚名,它真的可以匿名。在和其他功能函数合作的时候

l=[3,2,100,999,213,1111,31121,333]
print(max(l))

dic={'k1':10,'k2':100,'k3':30}


print(max(dic))
print(dic[max(dic,key=lambda k:dic[k])])
res = map(lambda x:x**2,[1,5,7,4,8])
for i in res:
    print(i)

输出
25
16
res = filter(lambda x:x>10,[5,8,11,9,15])
for i in res:
    print(i)

输出
15

面试题练一练

1.现有两个元组(('a'),('b')),(('c'),('d')),请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]

#答案一
test = lambda t1,t2 :[{i:j} for i,j in zip(t1,t2)]
print(test(t1,t2))
#答案二
print(list(map(lambda t:{t[0]:t[1]},zip(t1,t2))))
#还可以这样写
print([{i:j} for i,j in zip(t1,t2)])
复制代码
View Code

相关文章:

  • 2021-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-29
  • 2021-10-02
  • 2021-10-15
  • 2021-12-19
猜你喜欢
  • 2021-08-08
  • 2021-09-28
  • 2021-09-24
  • 2021-07-04
  • 2021-11-05
  • 2021-06-28
  • 2021-07-20
相关资源
相似解决方案