Python基础第十天:Python之内置函数、匿名函数

Python之内置函数,匿名函数

  内置函数

  我们一起来看看Python里面的内置函数,什么是内置函数?就是Python给我们提供的,拿来直接使用的函数,比如print、input等等。截止到Python版本3.6.2,现在Python一共为我们提供了68个内置函数,有些我们还没有使用过,还有一些是被封印了,要等我们学了新知识才能解开封印。今天我们就一起来认识一下Python的内置函数。这么多内置函数,我们该从何处学习起呢?   

 

   内置函数    
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()  

  作用域相关

  locals():函数会一字典的类型返回当前位置的全部局部变量

  globals():函数以字典的类型返回全部全局变量

  a = 1
  b = 2
  # 这两个一样,因为是在全局执行的。
  print(locals())
  print(globals())

  print("===========================")

  def func(argv):
      c = 2
      print(locals())
      print(globals())

  func(3)
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000000000216B240>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/pythonStudy12/day04/01.py', '__cached__': None, 'a': 1, 'b': 2}
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000000000216B240>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/pythonStudy12/day04/01.py', '__cached__': None, 'a': 1, 'b': 2}
===========================
{'c': 2, 'argv': 3}
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000000000216B240>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/pythonStudy12/day04/01.py', '__cached__': None, 'a': 1, 'b': 2, 'func': <function func at 0x00000000004B2EA0>}

  其他相关

  1、字符串类型代码的执行eval()、exec()、complie()

  evel():执行字符串类型的代码,并返回最终结果

  t = eval('2 + 2')
  print(t)

  n = 81
  t = eval('n + 4')
  print(t)

  eval('print(666)')
  4
  85
  666

  exec():执行字符串类型的代码

  s = """
  for i in range(10):
      print(i,end=" ")
  """
  exec(s)
  0 1 2 3 4 5 6 7 8 9 

  compile():将字符串类型的代码编译,代码对象能够通过exec()或者eval()来执行

  '''
  参数说明:   

  1. 参数source:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段。  

  2. 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可。  

  3. 参数model:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,model应指定为‘exec’;当source中只包含一个简单的求值表达式,model应指定为‘eval’;当source中包含了交互式命令语句,model应指定为'single'。
  '''
  #流程语句使用exec
  code1 ='for i in range(0,10):print(i,end=" ")'
  compile1 = compile(code1,'','exec')
  exec(compile1)
  print()
  #简单求值表达式用eval
  code1 = '1 + 2 + 3+ 4 + 5'
  compile1 = compile(code1,'','eval')
  sum = eval(compile1)
  print(sum)

  #交互语句用single
  code1 = 'name = input("please input your name:")'
  compile1 = compile(code1,'','single')
  exec(compile1)
  print(name)
  0 1 2 3 4 5 6 7 8 9 
  15
  please input your name:test
  test

  有返回值的字符串形式的代码用eval(),没有返回值的字符串形式的代码用exec(),一般不用compile()

  2、输入输出相关 input()、print()

  input():函数接受一个标准输入数据,返回string类型

  print():打印输出

  print(111,222,333,sep='*')

  print(111,end='')
  print(222)

  f = open('log','w',encoding='utf-8')
  print('写入文件',file=f,flush=True)
  f.close()

  f = open('log',encoding='utf-8')
  print(f.read())
  f.close()
  111*222*333
  111222
  写入文件

  3、内存相关:hash()、id()

   hash():获取一个对象(可哈希的对象:int、str、bool、tuple)的哈希值

  print(hash(123))
  print(hash('123'))
  print(hash('arg'))
  print(hash('alex'))
  print(hash(True))
  print(hash(False))
  print(hash((1,2,3)))
  123
  535330793523207778
  8935984426153707450
  6799085156391581394
  1
  0
  2528502973977326415

  id():用于获取对象的内存地址

  print(id(255))
  print(id('abc'))
  1494322128
  39935592

  4、文件相关

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

  5、模块相关:__import__()

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

  6、帮助

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

  print(help(list))
  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

  7、调用相关

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

  #数字、字符串
  print(callable(0))
  print(callable('123'))
  #函数
  def add(a, b):
      return a + b
  print(callable(add))
  #
  class A:
      def method(self):
          return 0
  print(callable(A))
  # 没有实现 __call__, 返回 False
  a = A()
  print(callable(a))

  class B:
      def __call__(self):
          return 0
  print(callable(B))
  # 实现 __call__, 返回 True
  b = B()
  print(callable(b))
  False
  False
  True
  True
  False
  True
  True

  8、查看内置函数

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

  # 获得当前模块的属性列表
  print(dir())
  # 查看列表的方法
  print(dir([]))
  ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
  ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

  迭代器、生成器相关

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

  next():内部实际使用了__next__ ()方法,放回迭代器的下一个项目

  # 首先获得Iterator对象:
  it = iter([1, 2, 3, 4, 5])
  # 循环:
  while True:
      try:
          # 获得下一个值:
          x = next(it)
          print(x,end=" ")
      except StopIteration:
          # 遇到StopIteration就退出循环
          break
  1 2 3 4 5 

  iter():用来生成迭代器(将一个可迭代对象、生成迭起器)

  from collections import Iterable
  from collections import Iterator

  l = [1,2,3,4,5]
  print(isinstance(l,Iterable))
  print(isinstance(l,Iterator))

  l1 = iter(l)
  print(isinstance(l1,Iterable))
  print(isinstance(l1,Iterator))
  True
  False
  True
  True

  基础数据类型相关

  1、数据类型

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

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

  print(bool())
  print(bool(''))
  print(bool(123))
  print(bool('123'))
  print(int())
  print(int('12'))
  print(int(3.6))
  # 将2进制的 0100 转化成十进制。结果为 4
  print(int('0100',base=2))  
  False
  False
  True
  True
  0
  12
  3
  4

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

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

  print(float(123))
  print(float('123'))

  print(complex(1,2))
  print(complex(1))
  # 当做字符串处理
  print(complex("1"))
  # 注意:这个地方在"+"号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错
  print(complex("1+2j"))
  123.0
  123.0
  (1+2j)
  (1+0j)
  (1+0j)
  (1+2j)

  进制转换:

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

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

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

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

  数学运算:

    abs():函数返回数字的绝对值

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

    round():保留浮点数的小数位数,默认保留整数。

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

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

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

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

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

  print(sum([1,2,3]))
  print(sum((1,2,3),100))

  print(min([1,2,3]))  # 返回此序列最小值

  ret = min([1,2,-5,])  # 返回此序列最小值
  print(ret)
  ret = min([1,2,-5,],key=abs)  # 按照绝对值的大小,返回此序列最小值
  print(ret)

  dic = {'a':3,'b':2,'c':1}
  # x为dic的key,lambda的返回值(即dic的值进行比较)返回最小的值对应的键
  print(min(dic,key=lambda x:dic[x]))

  print(max([1,2,3]))  # 返回此序列最大值
  
  ret = max([1,2,-5,],key=abs)  # 按照绝对值的大小,返回此序列最大值
  print(ret)

  dic = {'a':3,'b':2,'c':1}
  # x为dic的key,lambda的返回值(即dic的值进行比较)返回最大的值对应的键
  print(max(dic,key=lambda x:dic[x]))
  6
  106
  1
  -5
  1
  c
  3
  -5
  a

  列表和元组

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

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

  l = list((1,2,3))
  print(l)

  l = list({1,2,3})
  print(l)

  l = list({'k1':1,'k2':2})
  print(l)

  tu = tuple((1,2,3))
  print(tu)

  tu = tuple([1,2,3])
  print(tu)

  tu = tuple({'k1':1,'k2':2})
  print(tu)
  [1, 2, 3]
  [1, 2, 3]
  ['k1', 'k2']
  (1, 2, 3)
  (1, 2, 3)
  ('k1', 'k2')

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

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

  ite = reversed(['a',2,3,'c',4,2])
  for i in ite:
      print(i,end=" ")

  li = ['a','b','c','d','e','f','g']
  sli_obj = slice(3)
  print(li[sli_obj])

  sli_obj = slice(0,7,2)
  print(li[sli_obj])
  2 4 c 3 2 a ['a', 'b', 'c']
  ['a', 'c', 'e', 'g']

  str():将数据转化成字符串

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

  bytes():用于不同编码之间的转化

  s = '你好'
  bs = s.encode('utf-8')
  print(bs)
  s1 = bs.decode('utf-8')
  print(s1)
  bs = bytes(s,encoding='utf-8')
  print(bs)
  b = '你好'.encode('gbk')
  b1 = b.decode('gbk')
  print(b1.encode('utf-8'))
  b'\xe4\xbd\xa0\xe5\xa5\xbd'
  你好
  b'\xe4\xbd\xa0\xe5\xa5\xbd'
  b'\xe4\xbd\xa0\xe5\xa5\xbd'

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

  ret = bytearray('alex',encoding='utf-8')
  print(id(ret))
  print(ret)
  print(ret[0])
  ret[0] = 65
  print(ret)
  print(id(ret))
  35615608
  bytearray(b'alex')
  97
  bytearray(b'Alex')
  35615608

  memoryview()

  ret = memoryview(bytes('你好',encoding='utf-8'))
  print(len(ret))
  print(ret)
  print(bytes(ret[:3]).decode('utf-8'))
  print(bytes(ret[3:]).decode('utf-8'))

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

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

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

  #ord 输入字符找该字符编码的位置
  print(ord('a'))
  print(ord(''))

  #chr 输入位置数字找出其对应的字符
  print(chr(97))
  print(chr(20013))

  #是ascii码中的返回该值,不是就返回/u...
  print(ascii('a'))
  print(ascii(''))
  97
  20013
  a
  中
  'a'
  '\u4e2d'

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

  # repr 原形毕露
  print(repr('{"name":"alex"}'))
  print('{"name":"alex"}')
  '{"name":"alex"}'
  {"name":"alex"}

  数据集合

    dict():创建一个字典

    set():创建一个集合

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

  相关内置函数

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

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

  L = [('a', 1), ('c', 3), ('d', 4), ('b', 2), ]
  print(sorted(L, key=lambda x: x[1]))
  students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
  print(sorted(students, key=lambda s: s[2]))  # 按年龄排序
  print(sorted(students, key=lambda s: s[2], reverse=True))  # 按降序
  [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
  [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
  [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

  enumerate():枚举,返回一个枚举对象   

  for i in enumerate([1,2,3]):
      print(i)
  for i in enumerate([1,2,3],100):
      print(i)
  (0, 1)
  (1, 2)
  (2, 3)
  (100, 1)
  (101, 2)
  (102, 3)

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

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

  print(all([1,2,True,0]))
  print(any([1,'',0]))
  False
  True

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

  l1 = [1,2,3,]
  l2 = ['a','b','c',5]
  l3 = ('*','**',(1,2,3))
  for i in zip(l1,l2,l3):
      print(i)
  (1, 'a', '*')
  (2, 'b', '**')
  (3, 'c', (1, 2, 3))

  filter():过滤

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

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

  def square(x):  # 计算平方数
      return x ** 2

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

  匿名函数

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

  def calc(n):
      return n ** n
  print(calc(10))

  # 换成匿名函数
  calc = lambda n: n ** n
  print(calc(10))
  10000000000
  10000000000

 

  上面是我们对calc这个匿名函数的分析,下面给出了一个关于匿名函数格式的说明

  函数名 = lambda 参数 :返回值

  参数可以有多个,用逗号隔开
  匿名函数不管逻辑多复杂,只能写一行,且逻辑执行结束后的内容就是返回值
  返回值和正常的函数一样可以是任意数据类型

  我们可以看出,匿名函数并不是真的不能有名字

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

  匿名函数与内置函数举例:

  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])])
  31121
  k3
  100
  res = map(lambda x:x**2,[1,5,7,4,8])
  for i in res:
      print(i)
  1
  25
  49
  16
  64
  res = filter(lambda x:x>10,[5,8,11,9,15])
  for i in res:
      print(i)
  11
  15

 

posted @ 2018-05-14 12:09  你知道  阅读(206)  评论(0编辑  收藏  举报