内置函数2与匿名函数

一 内置函数2

  1 其他相关

  1.1  文件操作相关

  open:函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。

  1.2  模块相关

  __import__:函数用于动态加载类和函数 。

  1.3  帮助

  help:函数用于查看函数或模块用途的详细说明。

print(help(list))
Help on class list in module builtins:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __iadd__(self, value, /)
 |      Implement self+=value.
 |  
 |  __imul__(self, value, /)
 |      Implement self*=value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.n
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __reversed__(...)
 |      L.__reversed__() -- return a reverse iterator over the list
 |  
 |  __rmul__(self, value, /)
 |      Return self*value.
 |  
 |  __setitem__(self, key, value, /)
 |      Set self[key] to value.
 |  
 |  __sizeof__(...)
 |      L.__sizeof__() -- size of L in memory, in bytes
 |  
 |  append(...)
 |      L.append(object) -> None -- append object to end
 |  
 |  clear(...)
 |      L.clear() -> None -- remove all items from L
 |  
 |  copy(...)
 |      L.copy() -> list -- a shallow copy of L
 |  
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value
 |  
 |  extend(...)
 |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
 |  
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |  
 |  insert(...)
 |      L.insert(index, object) -- insert object before index
 |  
 |  pop(...)
 |      L.pop([index]) -> item -- remove and return item at index (default last).
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(...)
 |      L.remove(value) -> None -- remove first occurrence of value.
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(...)
 |      L.reverse() -- reverse *IN PLACE*
 |  
 |  sort(...)
 |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

None

Process finished with exit code 0

  1.4 调用相关

  callable:函数用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。

 1 >>>callable(0)
 2 False
 3 >>> callable("runoob")
 4 False
 5  
 6 >>> def add(a, b):
 7 ...     return a + b
 8 ... 
 9 >>> callable(add)             # 函数返回 True
10 True
11 >>> class A:                  #
12 ...     def method(self):
13 ...             return 0
14 ... 
15 >>> callable(A)               # 类返回 True
16 True
17 >>> a = A()
18 >>> callable(a)               # 没有实现 __call__, 返回 False
19 False
20 >>> class B:
21 ...     def __call__(self):
22 ...             return 0
23 ... 
24 >>> callable(B)
25 True
26 >>> b = B()
27 >>> callable(b)               # 实现 __call__, 返回 True
View Code

  1.5 查看内置属性

  dir:函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。

如果参数不包含__dir__(),该方法将最大限度地收集参数信息

1 >>>dir()   #  获得当前模块的属性列表
2 ['__builtins__', '__doc__', '__name__', '__package__', 'arr', 'myslice']
3 >>> dir([ ])    # 查看列表的方法
4 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
View Code

  2 迭代器生成相关

  range 函数可创建一个整数对象,一般用在 for 循环中

  next 内部实际使用了__next__方法,返回迭代器的下一个项目。

 1 it = iter([1, 2, 3, 4, 5])
 2 # 循环:
 3 while True:
 4     try:
 5         # 获得下一个值:
 6         x = next(it)
 7         print(x)
 8     except StopIteration:
 9         # 遇到StopIteration就退出循环
10         break
View Code

  iter 函数用来生成迭代器(讲一个可迭代对象,生成迭代器)。

  3 基础数据相关

  3.1 数字相关

  数据类型

  bool 用于将给定参数转换为布尔类型,如果没有参数,返回 False

  int 函数用于将一个字符串或数字转换为整型

1 print(int())  # 0
2 
3 print(int('12'))  # 12
4 
5 print(int(3.6))  # 3
6 
7 print(int('0100',base=2))  # 将2进制的 0100 转化成十进制。结果为 4
View Code

  float 函数用于将整数和字符串转换成浮点数

  complex 函数用于创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数

  进制转换

  bin 将十进制转换成二进制并返回

  oct 将十进制转化成八进制字符串并返回

  hex 将十进制转化成十六进制字符串并返回

1 print(bin(10),type(bin(10)))  # 0b1010 <class 'str'>
2 print(oct(10),type(oct(10)))  # 0o12 <class 'str'>
3 print(hex(10),type(hex(10)))  # 0xa <class 'str'>

  数据运算

  abs 函数返回数字的绝对值。

  divmod 计算除数与被除数的结果,返回一个包含商和余数的元组(a // b, a % b)

  round 保留浮点数的小数位数,默认保留整数

  pow 求x**y次幂。(三个参数为x**y的结果对z取余)

 1 print(abs(-5))  # 5
 2 
 3 print(divmod(7,2))  # (3, 1)
 4 
 5 print(round(7/3,2))  # 2.33
 6 print(round(7/3))  # 2
 7 print(round(3.32567,3))  # 3.326
 8 
 9 print(pow(2,3))  # 两个参数为2**3次幂
10 print(pow(2,3,3))  # 三个参数为2**3次幂,对3取余。
View Code

  sum 对可迭代对象进行求和计算(可设置初始值)

  min 返回可迭代对象的最小值(可加key,key为函数名,通过函数的规则,返回最小值)

  max 返回可迭代对象的最大值(可加key,key为函数名,通过函数的规则,返回最大值)

 1 print(sum([1,2,3]))
 2 print(sum((1,2,3),100))
 3 
 4 print(min([1,2,3]))  # 返回此序列最小值
 5 
 6 ret = min([1,2,-5,],key=abs)  # 按照绝对值的大小,返回此序列最小值
 7 print(ret)
 8 
 9 dic = {'a':3,'b':2,'c':1}
10 print(min(dic,key=lambda x:dic[x]))
11 # x为dic的key,lambda的返回值(即dic的值进行比较)返回最小的值对应的键
12 
13 
14 print(max([1,2,3]))  # 返回此序列最大值
15 
16 ret = max([1,2,-5,],key=abs)  # 按照绝对值的大小,返回此序列最大值
17 print(ret)
18 
19 dic = {'a':3,'b':2,'c':1}
20 print(max(dic,key=lambda x:dic[x]))
21 # x为dic的key,lambda的返回值(即dic的值进行比较)返回最大的值对应的键
View Code

  3.2 和数据结构相关

  列表和元组

  list 将一个可迭代对象转化成列表(如果是字典,默认将key作为列表的元素

  tuple 将一个可迭代对象转化成元祖(如果是字典,默认将key作为元祖的元素

 1 l = list((1,2,3))
 2 print(l)
 3 
 4 l = list({1,2,3})
 5 print(l)
 6 
 7 l = list({'k1':1,'k2':2})
 8 print(l)
 9 
10 tu = tuple((1,2,3))
11 print(tu)
12 
13 tu = tuple([1,2,3])
14 print(tu)
15 
16 tu = tuple({'k1':1,'k2':2})
17 print(tu)
View Code

  相关内置函数

  reversed 将一个序列翻转,并返回此翻转序列的迭代器

1 it=reversed([1,2,4,6,0])   #返回迭代器
2 for i in it:
3     print(i)
4 
5 0
6 6
7 4
8 2
9 1

  slice 构造一个切片对象,用于列表的切片

1 li=[1,2,3,6,4,7]
2 li_obj=slice(3)
3 print(li[li_obj],type(li_obj))
1 l1 = [1, 2, 3, 55, 77]
2 l2 = [-1, -2, 3, 55, -77, 88]
3 print(l1[1:4])
4 print(l2[1:4])
5 
6 rule = slice(1,6,2)
7 print(l1[rule])
8 print(l2[rule])

  字符串相关

  str 将数据转化成字符串

  format 与具体数据相关,用于计算各种小数,精算等

 1 #字符串可以提供的参数,指定对齐方式,<是左对齐, >是右对齐,^是居中对齐
 2 print(format('test', '<20'))
 3 print(format('test', '>20'))
 4 print(format('test', '^20'))
 5 
 6 #整形数值可以提供的参数有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None
 7 >>> format(3,'b') #转换成二进制
 8 '11'
 9 >>> format(97,'c') #转换unicode成字符
10 'a'
11 >>> format(11,'d') #转换成10进制
12 '11'
13 >>> format(11,'o') #转换成8进制
14 '13'
15 >>> format(11,'x') #转换成16进制 小写字母表示
16 'b'
17 >>> format(11,'X') #转换成16进制 大写字母表示
18 'B'
19 >>> format(11,'n') #和d一样
20 '11'
21 >>> format(11) #默认和d一样
22 '11'
23 
24 #浮点数可以提供的参数有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None
25 >>> format(314159267,'e') #科学计数法,默认保留6位小数
26 '3.141593e+08'
27 >>> format(314159267,'0.2e') #科学计数法,指定保留2位小数
28 '3.14e+08'
29 >>> format(314159267,'0.2E') #科学计数法,指定保留2位小数,采用大写E表示
30 '3.14E+08'
31 >>> format(314159267,'f') #小数点计数法,默认保留6位小数
32 '314159267.000000'
33 >>> format(3.14159267000,'f') #小数点计数法,默认保留6位小数
34 '3.141593'
35 >>> format(3.14159267000,'0.8f') #小数点计数法,指定保留8位小数
36 '3.14159267'
37 >>> format(3.14159267000,'0.10f') #小数点计数法,指定保留10位小数
38 '3.1415926700'
39 >>> format(3.14e+1000000,'F')  #小数点计数法,无穷大转换成大小字母
40 'INF'
41 
42 #g的格式化比较特殊,假设p为格式中指定的保留小数位数,先尝试采用科学计数法格式化,得到幂指数exp,如果-4<=exp<p,则采用小数计数法,并保留p-1-exp位小数,否则按小数计数法计数,并按p-1保留小数位数
43 >>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点
44 '3e-05'
45 >>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留1位小数点
46 '3.1e-05'
47 >>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留2位小数点
48 '3.14e-05'
49 >>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点,E使用大写
50 '3.14E-05'
51 >>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留0位小数点
52 '3'
53 >>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留1位小数点
54 '3.1'
55 >>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留2位小数点
56 '3.14'
57 >>> format(0.00003141566,'.1n') #和g相同
58 '3e-05'
59 >>> format(0.00003141566,'.3n') #和g相同
60 '3.14e-05'
61 >>> format(0.00003141566) #和g相同
62 '3.141566e-05'
View Code

  bytes 用于不同编码之间的转化 将unicode ---> bytes

 1 # s = '你好'
 2 # bs = s.encode('utf-8')
 3 # print(bs)
 4 # s1 = bs.decode('utf-8')
 5 # print(s1)
 6 # bs = bytes(s,encoding='utf-8')
 7 # print(bs)
 8 # b = '你好'.encode('gbk')
 9 # b1 = b.decode('gbk')
10 # print(b1.encode('utf-8')
View Code

  bytearry 返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。

  memoryview

  ord 输入字符找该字符编码的位置

  chr 输入位置数字找出其对应的字符

  ascii 是ascii码中的返回该值,不是就返回/u...

  repr 返回一个对象的string形式(原形毕露)

1 # %r  原封不动的写出来
2 # name = 'taibai'
3 # print('我叫%r'%name)
4 
5 # repr 原形毕露
6 print(repr('{"name":"alex"}'))
7 print('{"name":"alex"}')
View Code

  数据集合

  dict 创建一个字典

  set 创建一个集合

  frozenset 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素

  len 返回一个对象中元素的个数

  sorted 对所有可迭代的对象进行排序操作

1 students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
2 print(sorted(students, key=lambda s: s[2]))  # 按年龄排序
3 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
4 print(sorted(students, key=lambda s: s[2], reverse=True))  # 按降序
5 [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
6 print(sorted(students,key=lambda s:s[1]))
7 [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
View Code

  enumerate 在字典上是枚举、列举的意思,参数为可遍历/可迭代的对象(如列表、字符串),多用于在for循环中得到计数,利用它可以同时获得索引和值,

即需要index和value值的时候可以使用,enumerate()返回的是一个enumerate对象

 1 for i in enumerate([1,2,3]):
 2     print(i)
 4 (0, 1)
 5 (1, 2)
 6 (2, 3)
 7 
 8 for i in enumerate([1,2,3],100):
 9     print(i)
10 (100, 1)
11 (101, 2)
12 (102, 3)

  all 可迭代对象中,全都是True才是True

  any 可迭代对象中,有一个True 就是True

  zip 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回

列表长度与最短的对象相同

1 l1 = [1,2,3,]
2 l2 = ['a','b','c',5]
3 l3 = ('*','**',(1,2,3))
4 for i in zip(l1,l2,l3):
5     print(i)
6 
7 (1, 'a', '*')
8 (2, 'b', '**')
9 (3, 'c', (1, 2, 3))
View Code

  filter

1 filter 过滤 通过你的函数,过滤一个可迭代对象,返回的是True
2 类似于[i for i in range(10) if i > 3]
3 def func(x):return x%2 == 0
4 ret = filter(func,[1,2,3,4,5,6,7])
5 print(ret)
6 for i in ret:
7      print(i)

<filter object at 0x016F6810>
2
4
6

1 def func(x):
2     return x%2==0
3 ret=filter(func,li)
4 for i in ret:
5     print(i)
6 
7 ret=filter(lambda x:x%2==0,li )
8 for i in ret:
9     print(i)

  map 会根据提供的函数对指定序列做映射

 1 >>>def square(x) :            # 计算平方数
 2 ...     return x ** 2
 3 ... 
 4 >>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
 5 [1, 4, 9, 16, 25]
 6 >>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
 7 [1, 4, 9, 16, 25]
 8  
 9 # 提供了两个列表,对相同位置的列表数据进行相加
10 >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
11 [3, 7, 11, 15, 19]
 1 l1 = [1,2,3,4,5]
 2 def func(x):
 3     return x*x
 4 ret = map(func,l1)
 5 print(ret)
 6 for i in ret:
 7     print(i)
 8 
 9 for i in map(lambda x:x**2,l1):
10     print(i)

二 匿名函数

  匿名函数:为了解决那些功能很简单的需求而设计的一句话函数。

  

1 函数名 = lambda 参数 :返回值
2 
3 #参数可以有多个,用逗号隔开
4 #匿名函数不管逻辑多复杂,只能写一行,且逻辑执行结束后的内容就是返回值
5 #返回值和正常的函数一样可以是任意数据类型
原文地址:https://www.cnblogs.com/wdbgqq/p/9209579.html