14,内置函数,和匿名函数

作用域相关:

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

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


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

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

#这两个不一样,locals() {'argv': 3, 'c': 2}
#globals() {'__doc__': None, '__builtins__': <module 'builtins' (built-in)>, '__cached__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000024409148978>, '__spec__': None, '__file__': 'D:/lnh.python/.../内置函数.py', 'func': <function func at 0x0000024408CF90D0>, '__name__': '__main__', '__package__': None}
 

其他类型相关:

eval:执行字符串类型的代码,并返回最终结果。

print(eval('2+2'))
n = 61
print(eval('n + 3'))

eval('print(666)')

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

s = '''
for i in [1,2,3]:
    print(i)
'''
exec(s)

compile

'''
参数说明:   

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)'
>>> compile1 = compile(code1,'','exec')
>>> exec (compile1)


>>> #简单求值表达式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2)


>>> #交互语句用single
>>> code3 = 'name = input("please input your name:")'
>>> compile3 = compile(code3,'','single')
>>> name #执行前name变量不存在
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    name
NameError: name 'name' is not defined
>>> exec(compile3) #执行时显示交互命令,提示输入
please input your name:'pythoner'
>>> name #执行后name变量有值
"'pythoner'"

有返回值的字符串形式的代码用eval,没有返回值的字符串形式的代码用exec。

1.2.2输入输出相关 input print

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

print:打印输出

''' 源码分析
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
    """
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    file:  默认是输出到屏幕,如果设置为文件句柄,输出到文件
    sep:   打印多个值之间的分隔符,默认为空格
    end:   每一次打印的结尾,默认为换行符
    flush: 立即把内容输出到流文件,不作缓存
    """
'''

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

print(111,end='')
print(222)  #两行的结果 111222

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

1.2.3内存相关 hash id

  hash:获取一个对象(克哈希对象:int,str,bool,tuple)的哈希值。

print(hash('ddd'))#不可哈希,可变类型
print(hash(123))#可哈希,不可变数据类型。
print(hash((1,2)))#可哈希,不可变数据类型。
print(hash(True))#可哈希,不可变数据类型。
print(hash(False))#可哈希,不可变数据类型。

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

a = 123 #可哈希不可变数据类型
b = 123#可哈希不可变数据类型
print(id(a))
print(id(b))

c = '123'#不可哈希,可变数据类型
d = '123'#不可哈希,可变数据类型
print(id(c))
print(id(d))

文件操作相关:

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

 模块相关:

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

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.2.6调用相关

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

age = 14
def func1():
    print(111)
    # return 111
    age = 15
    print(id(age))
print(age)
func1()
print(id(age))
print(callable(age))
print(callable(func1))

1.2.7查看内置属性

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

>dir()   #  获得当前模块的属性列表
['__builtins__', '__doc__', '__name__', '__package__', 'arr', 'myslice']
>>> dir([ ])    # 查看列表的方法
['__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']

 

1.3迭代器生成器相关:

  range:函数可创建一个证书对象,一般用在for循环中。

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

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

 

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

  

from collections import Iterable
from collections import Iterator
l = [1,2,3]
print(isinstance(l,Iterable))
print(isinstance(l,Iterator))
with open('log',encoding='utf-8') as f1:
        print(isinstance(f1,Iterable))
        print(isinstance(f1,Iterator))
进制转换
  bin:将十进制转换成二进制并返回。
  oct:将十进制转化成八进制字符串并返回。
  hex:将十进制转化成十六进制字符串并返回。
print(bin(100))
print(oct(10))
print(hex(13))
print(hex(18))

数字运算(7):

  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))  # 2.33
print(round(7/3))  # 2
print(round(3.32567,3))  # 3.326

print(pow(2,3))  # 两个参数为2**3次幂
print(pow(2,3,3))  # 三个参数为2**3次幂,对3取余。

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

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

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

a = sum([int(i) for i in input('请输入数字').split(',')]);print(a)
print(sum(range(1,100,2)))
print(min([1,3,5,7, -4],key=abs)) #1
print(max([1,3,5,7, -9],key=abs)) #-9
dic = {'a':3,'b':2,'c':1}
print(min(dic,key=lambda x:dic[x]))#c
print(max(dic,key=lambda x:dic[x]))#a
 

1.4.1数字相关(14)

  数据类型(4)

  bool:用于将给定参数转换成bool类型,如果没有参数,返回False。

  int:函数用于讲一个字符串或者数字类型转换为整形。

  float:函数用于将证书和字符串转换成浮点数。

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

 1.4.2和数据结构相关(24)

  列表和元组(2)

    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)

相关内置函数(2)

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

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

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

sli_obj = slice(0,7,2)
print(li[sli_obj])


str1 = 'sfdsfw2gdf'
li = []
a = reversed(str1)
for i in a:
li.append(i)
a1 = ''.join(li)
print(a1)

字符串相关(9):

    str:将数据转化成字符串。

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

#字符串可以提供的参数,指定对齐方式,<是左对齐, >是右对齐,^是居中对齐
print(format('test', '<20'))
print(format('test', '>20'))
print(format('test', '^20'))

#整形数值可以提供的参数有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None
>>> format(3,'b') #转换成二进制
'11'
>>> format(97,'c') #转换unicode成字符
'a'
>>> format(11,'d') #转换成10进制
'11'
>>> format(11,'o') #转换成8进制
'13'
>>> format(11,'x') #转换成16进制 小写字母表示
'b'
>>> format(11,'X') #转换成16进制 大写字母表示
'B'
>>> format(11,'n') #和d一样
'11'
>>> format(11) #默认和d一样
'11'

#浮点数可以提供的参数有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None
>>> format(314159267,'e') #科学计数法,默认保留6位小数
'3.141593e+08'
>>> format(314159267,'0.2e') #科学计数法,指定保留2位小数
'3.14e+08'
>>> format(314159267,'0.2E') #科学计数法,指定保留2位小数,采用大写E表示
'3.14E+08'
>>> format(314159267,'f') #小数点计数法,默认保留6位小数
'314159267.000000'
>>> format(3.14159267000,'f') #小数点计数法,默认保留6位小数
'3.141593'
>>> format(3.14159267000,'0.8f') #小数点计数法,指定保留8位小数
'3.14159267'
>>> format(3.14159267000,'0.10f') #小数点计数法,指定保留10位小数
'3.1415926700'
>>> format(3.14e+1000000,'F')  #小数点计数法,无穷大转换成大小字母
'INF'

#g的格式化比较特殊,假设p为格式中指定的保留小数位数,先尝试采用科学计数法格式化,得到幂指数exp,如果-4<=exp<p,则采用小数计数法,并保留p-1-exp位小数,否则按小数计数法计数,并按p-1保留小数位数
>>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点
'3e-05'
>>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留1位小数点
'3.1e-05'
>>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留2位小数点
'3.14e-05'
>>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点,E使用大写
'3.14E-05'
>>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留0位小数点
'3'
>>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留1位小数点
'3.1'
>>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留2位小数点
'3.14'
>>> format(0.00003141566,'.1n') #和g相同
'3e-05'
>>> format(0.00003141566,'.3n') #和g相同
'3.14e-05'
>>> format(0.00003141566) #和g相同
'3.141566e-05'

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

s = 'zhangyajie'
s1 = s.encode('utf-8')
print(s1)
s2 = s1.decode('utf-8')
print(s2)
bs = bytes(s,encoding='utf-8')
print(bs)
b = '你好'.encode('utf-8');print(b)
b1 = b.decode('utf-8');print(b1)
print(b1.encode('gbk'))

    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))

    

    rd:输入字符找该字符编码的位置

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

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

print(ord('a'))
print(ord(''))

print(chr(97))
print(chr(20013))

print(ascii('a'))
print(ascii(''))

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

name = 'alex'
print('我叫%r' % name)
print(repr('{"name":"alex"}'))
print(type('{"name":"alex"}'))

 数据集合(3)

    dict:创建一个字典。

    set:创建一个结合。

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

set1 = frozenset({1, 2, 3, 'alex'})
print(set1,type(set1))

    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 x:x[2]))

students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
print(sorted(students,key=lambda x:x[1]))

    enumerate:枚举,返回一个枚举对象。

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

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

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

 

# all  可迭代对象中,全都是True才是True
# any  可迭代对象中,有一个True 就是True
# print(all([1,2,True,0]))
# print(any([1,'',0]))

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

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

    filter:过滤。筛选

ret = filter(lambda x:x % 2 == 0,y)
for i in ret:
    print(i)

ef func(x):
    return x % 2 == 0
ret = filter(func,[1, 2, 3, 4, 5, 6, 7])
print(ret)
for i in ret:
    print(i)

 

    map:会根据提供的函数对执行序列做映射。返回一个迭代器

a =map(lambda x:x**2,[1,2,3])
print('__iter__' in dir(a))
print('__next__' in dir(a))
for i in a:
print(i)

 

 匿名函数 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])])
ret = map(lambda x:x**2,[1,5,7,4,8])
for i in ret:
    print(i)
ret = filter(lambda x:x>10,[5,8,11,9,15])
for i in ret:
    print(i)

 

  

posted @ 2018-05-17 19:52  Mr~Zhang  阅读(151)  评论(0编辑  收藏  举报