码迷,mamicode.com
首页 > 其他好文 > 详细

内置函数(3)

时间:2016-08-05 17:32:50      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

23、内置函数(3)
     1、dir():快速查看对象提供了哪些功能。
>>> dir(list)
[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__iadd__‘, ‘__imul__‘, ‘__init__‘, ‘__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‘]
>>>
2、help():读取帮助信息,即源码。
3、divmod():做分页时会用到。
>>> divmod(97,10) #即97除以10 得9 余7  
(9, 7)
>>>
n1,n2 = divmod(97,10)
4、enumerate():做枚举。
>>> list = [11,22,33]
>>> for i in enumerate(list):
...     print(i)
...
(0, 11)
(1, 22)
(2, 33)
5、isinstance():用于判断对象是不是每个类的实例。
>>> s = ‘alex‘
>>> isinstance(s,str)
True
6、filter():filter(函数,可迭代的对象),筛选符合的元素。
     filter内部循环第二个参数,让每个循环元素执行这个函数,如果函数返回True,表示元素合法,将元素添加到结果中。
     >>> li = [11,22,33,44]
>>> def f2(a):
...     if a>22:
...         return True
...
>>> ret = filter(f2,li)
>>> print(list(ret))
[33, 44]
或者采用lambda函数:
>>> ret1 = filter(lambda a1: a1>33,li)
>>> print(list(ret 1))
[44]
7、map():map(函数,可迭代的对象(可以for循环的对象))将函数的返回值添加到结果中。
>>> li = [11,22,33,44]
>>> def f3(a):
...     return a + 100
...
>>> ret = map(f3,li)
>>> print(list(ret))
[111, 122, 133, 144]
或者lambda函数:
>>> ret1 = map(lambda a:a+200,li)
>>> print(list(ret1))
[211, 222, 233, 244]
8、globals()和locals():全局变量和局部变量
     >>> name = ‘alex‘
>>> def f2():
...     a = 123
...     b = 345
...     print(locals())
...     print(global
global    globals( 
...     print(globals())
...
>>> f2()
{‘a‘: 123, ‘b‘: 345}
{‘tab‘: <module ‘tab‘ from ‘/usr/local/python3/lib/python3.5/tab.py‘>, ‘ret1‘: <map object at 0x7f2f93b3e780>, ‘ret‘: <map object at 0x7f2f93b3e7b8>, ‘__spec__‘: None, ‘li‘: [11, 22, 33, 44], ‘name‘: ‘alex‘, ‘f3‘: <function f3 at 0x7f2f93b27a60>, ‘__name__‘: ‘__main__‘, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘__doc__‘: None, ‘__package__‘: None, ‘f2‘: <function f2 at 0x7f2f93b279d8>, ‘__loader__‘: <class ‘_frozen_importlib.BuiltinImporter‘>}
9、hash():将对象转换成hash值。
10、len():python2中只能以字节的方式查看他的len。python3以字符。
     >>> s = ‘张杰‘
>>> print(len(s))
2
>>> s1 = bytes(s,encoding=‘utf-8‘)
>>> print(len(s1))
6
11、max(),min(),sum()分别是最大,最小和求和。

内置函数(3)

标签:

原文地址:http://www.cnblogs.com/cfj271636063/p/5742065.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!