zoukankan      html  css  js  c++  java
  • 【python】重要的内置函数

    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'>
    
  • 相关阅读:
    CF703D Mishka and Interesting sum
    CF697D Puzzles
    SCOI2017酱油记
    [BZOJ4730][清华集训2016][UOJ266] Alice和Bob又在玩游戏
    BZOJ4311:向量
    BZOJ4520: [Cqoi2016]K远点对
    BZOJ4555: [Tjoi2016&Heoi2016]求和
    [Codechef November Challenge 2012] Arithmetic Progressions
    agc040
    补题
  • 原文地址:https://www.cnblogs.com/paulwinflo/p/12261523.html
Copyright © 2011-2022 走看看