一、内置函数:

     Python给你提供的,拿来直接用的函数,比如print、input等等,就是内置函数。

     截止到Python版本3.6.2,现在Python一共为我们提供了68个内置函数。

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

   1、作用域相关:

     ***** 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}

locals和globals

   2、字符串类型代码的执行:eval、exec、compile

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

eval('2 + 2')  #

n=81
eval("n + 4") # eval('print(666)') #

eval

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

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

exec

     ** compile:将字符串类型的代码编译。代码对象能够通过exec语句来执行或者eval()进行求值。

       注:有返回值的字符串形式的代码用eval,没有返回值的字符串形式的代码用exec,一般不用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'"

compile

    3、输入输出相关: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)

print

    4、内存相关:hash、id

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

print(hash(12322))
print(hash(''))
print(hash('arg'))
print(hash('alex'))
print(hash(True))
print(hash(False))
print(hash((1,2,3))) '''
-2996001552409009098
-4637515981888139739
1
2528502973977326415
'''

hash

     *** id:用于获取对象的内存地址。

print(id(123))  #
print(id('abc')) #

id

    5、文件操作相关:open

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

    6、模块相关:__imoort__

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

    7、帮助:help

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

help

    8、调用相关:callable

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

>>>callable(0)
False
>>> callable("runoob")
False >>> def add(a, b):
... return a + b
...
>>> callable(add) # 函数返回 True
True
>>> class A: # 类
... def method(self):
... return 0
...
>>> callable(A) # 类返回 True
True
>>> a = A()
>>> callable(a) # 没有实现 __call__, 返回 False
False
>>> class B:
... def __call__(self):
... return 0
...
>>> callable(B)
True
>>> b = B()
>>> callable(b) # 实现 __call__, 返回 True

callable

    9、查看内置属性:dir

     *** 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']

dir

    10、迭代器生成器相关:range、next、iter

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

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

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

next

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

from collections import Iterable
from collections import Iterator
l = [1,2,3]
print(isinstance(l,Iterable)) # True
print(isinstance(l,Iterator)) # False l1 = iter(l)
print(isinstance(l1,Iterable)) # True
print(isinstance(l1,Iterator)) # True

iter

    11、基础数据类型相关:

     数据类型(4):

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

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

print(int())  #

print(int(''))  #

print(int(3.6))  # 3 取整

print(int('',base=2))  # 将2进制的 0100 转化成十进制。结果为 4

int

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

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

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

complex

    进制转换(3):

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

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

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

print(bin(10),type(bin(10)))  # 0b1010 <class 'str'>   0b二进制
print(oct(10),type(oct(10))) # 0o12 <class 'str'> 0o八进制
print(hex(10),type(hex(10))) # 0xa <class 'str'> 0x十六进制

进制转换

     

    数学运算(7):

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

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

     *** round:保留浮点数的小数位数,默认保留整数(四舍五入)。

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

print(abs(-5))  #

print(divmod(7,2))  # (3, 1)

print(round(7/3,2))  # 2.33
print(round(7/3)) #
print(round(3.32567,3)) # 3.326 print(pow(2,3)) # 两个参数为2**3次幂
print(pow(2,3,3)) # 三个参数为2**3次幂,对3取余。

abs、divmod、round、pow

     ***** 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,],key=abs) # 按照绝对值的大小,返回此序列最小值
print(ret) dic = {'a':3,'b':2,'c':1}
print(min(dic,key=lambda x:dic[x]))
# x为dic的key,lambda的返回值(即dic的值进行比较)返回最小的值对应的键 print(max([1,2,3])) # 返回此序列最大值 ret = max([1,2,-5,],key=abs) # 按照绝对值的大小,返回此序列最大值
print(ret) dic = {'a':3,'b':2,'c':1}
print(max(dic,key=lambda x:dic[x]))
# x为dic的key,lambda的返回值(即dic的值进行比较)返回最大的值对应的键 [('alex',1000),('太白',18),('wusir',500)]
求出年龄最小的那个元组 # 第一种:
ls = [('alex',1000),('太白',18),('wusir',500)]
min1 = min([i[1] for i in ls])
for i in ls:
if i[1]==min1:
print(i) # 第二种:
def func(x):
return x[1] # 1000 18 500
print(min([('alex',1000),('太白',18),('wusir',500)],key=func)) # 1,他会将iterable的每一个元素当做函数的参数传进去。
# 2,他会按照返回值去比较大小。
# 3,返回的是 遍历的元素 x. dic = {'a':3,'b':2,'c':1} # 第一种:
def func1(x):
return dic[x]
print(min(dic,key=func1)) # 第二种:
def func2(x):
return x[1]
print(min(dic.items(),key=func2))

sum、min、max

《Python》 内置函数的更多相关文章

  1. python内置函数

    python内置函数 官方文档:点击 在这里我只列举一些常见的内置函数用法 1.abs()[求数字的绝对值] >>> abs(-13) 13 2.all() 判断所有集合元素都为真的 ...

  2. python 内置函数和函数装饰器

    python内置函数 1.数学相关 abs(x) 取x绝对值 divmode(x,y) 取x除以y的商和余数,常用做分页,返回商和余数组成一个元组 pow(x,y[,z]) 取x的y次方 ,等同于x ...

  3. Python基础篇【第2篇】: Python内置函数(一)

    Python内置函数 lambda lambda表达式相当于函数体为单个return语句的普通函数的匿名函数.请注意,lambda语法并没有使用return关键字.开发者可以在任何可以使用函数引用的位 ...

  4. [python基础知识]python内置函数map/reduce/filter

    python内置函数map/reduce/filter 这三个函数用的顺手了,很cool. filter()函数:filter函数相当于过滤,调用一个bool_func(只返回bool类型数据的方法) ...

  5. Python内置函数进制转换的用法

    使用Python内置函数:bin().oct().int().hex()可实现进制转换. 先看Python官方文档中对这几个内置函数的描述: bin(x)Convert an integer numb ...

  6. Python内置函数(12)——str

    英文文档: class str(object='') class str(object=b'', encoding='utf-8', errors='strict') Return a string  ...

  7. Python内置函数(61)——str

    英文文档: class str(object='') class str(object=b'', encoding='utf-8', errors='strict') Return a string ...

  8. 那些年,很多人没看懂的Python内置函数

    Python之所以特别的简单就是因为有很多的内置函数是在你的程序"运行之前"就已经帮你运行好了,所以,可以用这个的特性简化很多的步骤.这也是让Python语言变得特别的简单的原因之 ...

  9. Python 内置函数笔记

    其中有几个方法没怎么用过, 所以没整理到 Python内置函数 abs(a) 返回a的绝对值.该参数可以是整数或浮点数.如果参数是一个复数,则返回其大小 all(a) 如果元组.列表里面的所有元素都非 ...

  10. 【转】实习小记-python 内置函数__eq__函数引发的探索

    [转]实习小记-python 内置函数__eq__函数引发的探索 乱写__eq__会发生啥?请看代码.. >>> class A: ... def __eq__(self, othe ...

随机推荐

  1. 51nod 1050 循环数组最大子段和 单调队列优化DP

    题目链接: http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1050 这个呢,这个题之前 求一遍最大值  然后求一遍最小值 ...

  2. Linux的内存分页管理【转】

    内存是计算机的主存储器.内存为进程开辟出进程空间,让进程在其中保存数据.我将从内存的物理特性出发,深入到内存管理的细节,特别是了解虚拟内存和内存分页的概念. 内存 简单地说,内存就是一个数据货架.内存 ...

  3. POJ 3162 Walking Race(树形dp+单调队列 or 线段树)

    http://poj.org/problem?id=3162 题意:一棵n个节点的树.有一个屌丝爱跑步,跑n天,第i天从第i个节点开始跑步,每次跑到距第i个节点最远的那个节点(产生了n个距离),现在要 ...

  4. 实现简单的ORM

    介绍 本篇将介绍实现简单的ORM,即:对数据表的通用操作:增.删.改.查 数据访问层 数据访问层类图 类说明: 1.DbProvider(供应):为数据操作提供基本对象,如:连接.操作对象.事务... ...

  5. 【Python】【环境搭建】

    [环境配置] Windows : http://blog.csdn.net/zhunianguo/article/details/53524792 [Pycharm] pyCharm最新2018激活码 ...

  6. BM25 调参调研

    1. 搜索 ES 计算文本相似度用的 BM25,参数默认,不适合电商场景,可调整 BM25 参数使其适用于电商短文本场景 2. k1.b.tf.L.tfScore 的关系如下图红框内所示(注:这里的 ...

  7. Win7下怎么设置让远程桌面连接记住密码下次登录不需再输入

    远程桌面连接功能想必大家都不会陌生吧,特别是使用VPS服务器的用户们经常会用到,为了服务器的安全每次都会把密码设置的很复制,但是这样也有一个麻烦,就是每次要桌面远程连接的时候都要输入这么复杂的密码,很 ...

  8. 学以致用 ---- vue子组件→父组件通信

    之前写过一篇关于 vue2.0中v-on绑定自定义事件 的随笔,但是今天实际应用的时候才发现根本就不理解,下面是实际工作中遇到的问题: [情景描述]页面中的[下拉搜索组件],因为多个页面中用到,所以抽 ...

  9. 《剑指offer》第四题(二维数组中的查找)

    // 二维数组中的查找 // 题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按 // 照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个 // 整数,判断数组 ...

  10. docker相关杂项

    代理 在vscode里build image习惯了,但是今天 从docker hub上pull python镜像,最后一个层,始终是waiting状态,pull不下来 好像不能临时.只能设置 http ...