菜比之路

走菜比的路,让大牛说去吧
  博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

【python】重要的内置函数

Posted on 2020-02-04 21:25  毕加索的ma  阅读(254)  评论(0编辑  收藏  举报

callable():可调用返回 True,否则返回 False。

a=10
def test():
    print("this is test")

print(callable(a))
#>>>False
print(callable(test))
#>>>True

filter():过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。filter(function, iterable)

old_list=filter(lambda n:n %2==0,range(10))
print(old_list)
#>>><filter object at 0x000001BEE29E6F60>
new_list=list(old_list)
print(new_list)
#>>>[0, 2, 4, 6, 8]

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

old_list=map(lambda n:n *2,range(10))
print(old_list)
#>>><filter object at 0x000001BEE29E6F60>
new_list=list(old_list)
print(new_list)
#>>>[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

reduce() 函数会对参数序列中元素进行累积。

from functools import  reduce
old_list=reduce(lambda x,y:x+y,range(10))
print(old_list)
#>>>45

round() 方法返回浮点数 的四舍五入值,round( x [, n] ),n -- 表示从小数点位数,其中 x 需要四舍五入,默认值为 0。

 

 

print(round(3.1415))
#>>>3
print(round(3.1415,1))
#>>>3.1
print(round(3.1415,2))
#>>>3.14

dir():返回对象的属性列表。

import  time
print(dir(time))

vars():返回对象的属性列表属性和属性值的字典对

import  time
print(vars(time))

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

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(enumerate(seasons))
#>>><enumerate object at 0x000002A1A2A856C0>
print(list(enumerate(seasons)))
#>>>[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

repr() 和eval(): 字典和字符串的相互转换

dict = {'runoob': 'runoob.com', 'google': 'google.com'}
dict_str=repr(dict)
print(type(dict_str))
#>>><class 'str'>
dict_new=eval(dict_str)
print(type(dict_new))
#>>><class 'dict'>