内置函数2

一、内置函数详情

1、filter(function, iterable)

功能:通过function过滤条件,去获取iterable中你想要的数据。

 

>>> res = filter(lambda n:n>5,range(10)) 
>>> res     #得到一个迭代器
<filter object at 0x0000000003093BE0>
>>> for i in res:
    print(i)
6
7
8
9

 

2、map(function, iterable)

功能:对传入的每一个值进行处理,处理完了再返回,再把原来的结果覆盖掉。

>>> res = map(lambda n:n*2,range(5))  #n*2是处理方式
>>> res
<map object at 0x00000000031B4BE0>
>>> for i in res:
    print(i)
0
2
4
6
8

3、reduce(function,iterable)

功能:把一组可迭代序列通过function函数操作,元素之间相加或者相乘操作。

>>> from functools import reduce
>>> res = reduce(lambda x,y:x+y,range(10))  #x+y的值赋给x,rang(10)中的每个元素赋给y
>>> res
45
>>> res = reduce(lambda x,y:x*y,range(1,10)) #x*y的值赋给x,rang(10)中的每个元素赋给y
>>> res
362880

4、float([x])

功能:把一个浮点类型的字符串转换为浮点类型的数据。

>>> float('+1.23')
1.23
>>> float('   -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf

5、format(value[, format_spec])

功能:格式话字符串,详细使用:猛击这里

6、frozenset([iterable])

功能:把集合变成一个不可变的集合

>> res = frozenset([1,2,3,4,3])
>>> res
frozenset({1, 2, 3, 4})   #去重的,不可变的集合
>>> dir(res)   #没有可变的方法
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__iter__', '__le__',
 '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__',
'__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__',
'__subclasshook__', '__xor__', 'copy', 'difference', 'intersection', 'isdisjoint', 'issubset',
'issuperset', 'symmetric_difference', 'union']

 注:set()是可变的

7、getattr(object, name[, default])

功能:这边是类那边的,后续再讲。

8、globals()

功能:返回当前这个python文件中的所有变量的key-value,变量是key,值是value

print(globals())
 
#输出
{'__spec__': None, '__name__': '__main__', '__file__': 'D:/PycharmProjects/pyhomework
/day4/内置函数/内置函数.py', '__doc__': None, '__package__': None, '__loader__':
<_frozen_importlib_external.SourceFileLoader object at 0x0000000000695B00>,
'__cached__': None, '__builtins__': <module 'built

注:可以判断一个文件中的变量是否存在,而globals()只能打印全局变量

9、hash(object)

功能:反射出一个对象的对应的hash值。

>>> hash('seven')
2313972277536963491
>>> hash(255)
255
>>> hash('a')
6806508886604307842

这个有什么用呐?

 先看下面的图:

 

看上面的图我们知道,如果一张表中5百万个用户信息,以我们现在的知识,只能用for循环去查找,那样的话,效率会很低。那我们怎么办呢?我们可以这样,就是把每一个姓名对应有一对应的值,然后通过对应的key值去定位,key值是放在一个列表中,当我们去查找某个key值时,可以折半查找,这样大大减少了查找时间,提高效率,这种也叫二分法查找,后面会有对应的博客专门写这一块的。 

posted @ 2017-08-27 17:59  七天&七天  阅读(111)  评论(0编辑  收藏  举报