zoukankan      html  css  js  c++  java
  • python内建函数(不完全)

    各位还是参考官方文档吧,我这些是自己感觉重要和常用的

    abs()
    all(iterable) 如果迭代序列中所有的元素都为真,或者迭代序列为空的时候返回True。等价于:
    def all(iterable):
        for element in iterable:
            if not element:
                return False
        return True
    all(iterable) 如果迭代序列中所有的元素都为真,返回True。等价于
    def any(iterable):
        for element in iterable:
            if element:
                return True
        return False
    complex()创建复数:
    >>> complex(1,2)
    (1+2j)
    >>> complex(1)
    (1+0j)
    delattr(object, name)
    For example, delattr(x,'foobar') is equivalent to del x.foobar.
    dict()创建字典
    dir()
    >>> import struct
    >>> dir()   # show the names in the module namespace
    ['__builtins__', '__doc__', '__name__', 'struct']
    >>> dir(struct)   # show the names in the struct module
    ['Struct', '__builtins__', '__doc__', '__file__', '__name__',
     '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
     'unpack', 'unpack_from']
    >>> class Shape(object):
            def __dir__(self):
                return ['area', 'perimeter', 'location']
    >>> s = Shape()
    >>> dir(s)
    ['area', 'perimeter', 'location']
    divmod(I,j)返回以商和余数组成的元祖:
    >>> divmod(10,3)
    (3, 1)
    enumerate(sequence[, start=0])
    >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
    >>> list(enumerate(seasons))
    [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
    >>> list(enumerate(seasons, start=1))
    [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
    其实也就等价于:
    def enumerate(sequence, start=0):
        n = start
        for elem in sequence:
            yield n, elem
            n += 1
    eval(expression[, globals[, locals]])
    >>> x = 1
    >>> print eval('x+1')
    2
    filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item foritem in iterable if item] if function is None.
    getattr(object, name[, default])
     For example, getattr(x, 'foobar') is equivalent to x.foobar. 
    hasattr(object, name)
    help([object])¶
    hex(x) 将整形x转化为16进制字符串,如果想要转化浮点型,可以使用float.hex(x)
    id(object) 对象的内存地址
    input([prompt]) Equivalent to eval(raw_input(prompt)).
    isinstance(object, classinfo)
    issubclass(class, classinfo)
    iter(o[, sentinel]) 迭代o,直到指和sentinel相等。例如:reads a file until the readline() method returns an empty string:
    with open('mydata.txt') as fp:
        for line in iter(fp.readline, ''):
            process_line(line)
    map(function, iterable, ...) Apply function to every item of iterable and return a list of the results.
    max(iterable[, args...][, key])
    min(iterable[, args...][, key])
    next(iterator[, default])
    oct(x)
    Convert an integer number (of any size) to an octal string. The result is a valid Python expression.
    open(name[, mode[, buffering]])
    property([fget[, fset[, fdel[, doc]]]])
    class C(object):
        def __init__(self):
            self._x = None
    
        def getx(self):
            return self._x
        def setx(self, value):
            self._x = value
        def delx(self):
            del self._x
        x = property(getx, setx, delx, "I'm the 'x' property.")
    创建只读属性:这个属性的值就不能修改了
    class Parrot(object):
        def __init__(self):
            self._voltage = 100000
    
        @property
        def voltage(self):
            """Get the current voltage."""
            return self._voltage
    
    
    class C(object):
        def __init__(self):
            self._x = None
    
        @property
        def x(self):
            """I'm the 'x' property."""
            return self._x
    
        @x.setter
        def x(self, value):
            self._x = value
    
        @x.deleter
        def x(self):
            del self._x
    range([start], stop[, step])
    >>> range(10)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> range(1, 11)
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> range(0, 30, 5)
    [0, 5, 10, 15, 20, 25]
    >>> range(0, 10, 3)
    [0, 3, 6, 9]
    >>> range(0, -10, -1)
    [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
    >>> range(0)
    []
    >>> range(1, 0)
    []
    reduce(function, iterable[, initializer])
    Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned.
    round(x[, n])
    >>> round(1.12313,2)
    1.12
    slice([start], stop[, step])
    sorted(iterable[, cmp[, key[, reverse]]])
    staticmethod(function)
    Return a static method for function.
    class C:
        @staticmethod
        def f(arg1, arg2, ...): ...
    sum(iterable[, start])
    tuple([iterable])
    >>> tuple("ada")
    ('a', 'd', 'a')
    zip([iterable, ...])
    zip() in conjunction with the * operator can be used to unzip a list:
    >>> x = [1, 2, 3]
    >>> y = [4, 5, 6]
    >>> zipped = zip(x, y)
    >>> zipped
    [(1, 4), (2, 5), (3, 6)]
    >>> x2, y2 = zip(*zipped)
    >>> x == list(x2) and y == list(y2)
    True
    
    >>> float.fromhex('0x3.a7p10')
    3740.0
    
    >>> lists = [[]] * 3
    >>> lists
    [[], [], []]
    >>> lists[0].append(3)
    >>> lists
    [[3], [3], [3]]
    
    >>> lists = [[] for i in range(3)]
    >>> lists[0].append(3)
    >>> lists[1].append(5)
    >>> lists[2].append(7)
    >>> lists
    [[3], [5], [7]]
    
    >>> "The sum of 1 + 2 is {0}".format(1+2)
    'The sum of 1 + 2 is 3'
    
    >>> "they're bill's friends from the UK".title()
    "They'Re Bill'S Friends From The Uk"
    
    >>> print '%(language)s has %(number)03d quote types.' % \
    ...       {"language": "Python", "number": 2}
    Python has 002 quote types.
    
    >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
    >>> keys = dishes.viewkeys()
    >>> values = dishes.viewvalues()
    
    >>> # iteration
    >>> n = 0
    >>> for val in values:
    ...     n += val
    >>> print(n)
    504
    
    >>> # keys and values are iterated over in the same order
    >>> list(keys)
    ['eggs', 'bacon', 'sausage', 'spam']
    >>> list(values)
    [2, 1, 1, 500]
    
    >>> # view objects are dynamic and reflect dict changes
    >>> del dishes['eggs']
    >>> del dishes['sausage']
    >>> list(keys)
    ['spam', 'bacon']
    
    >>> # set operations
    >>> keys & {'eggs', 'bacon', 'salad'}
    {'bacon'}
    
    >>> v = memoryview('abcefg')
    >>> v[1]
    'b'
    >>> v[-1]
    'g'
    >>> v[1:4]
    <memory at 0x77ab28>
    >>> v[1:4].tobytes()
    'bce'
    
    >>> data = bytearray('abcefg')
    >>> v = memoryview(data)
    >>> v.readonly
    False
    >>> v[0] = 'z'
    >>> data
    bytearray(b'zbcefg')
    >>> v[1:4] = '123'
    >>> data
    bytearray(b'z123fg')
    >>> v[2] = 'spam'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: cannot modify size of memoryview object
    
    >>> m = memoryview("abc")
    >>> m.tobytes()
    'abc'
    
    >>> memoryview("abc").tolist()
    [97, 98, 99]
    

      

  • 相关阅读:
    3.19 DAY2
    3.18 DAY1
    MySql Scaffolding an Existing Database in EF Core
    asp.net core 2.0 后台定时自动执行任务
    c#中枚举类型 显示中文
    fullCalendar使用经验总结
    Web APP 日期选择控件
    【转】剖析异步编程语法糖: async和await
    【转】Entity Framework 复杂类型
    【转】EF Code First 学习笔记:约定配置
  • 原文地址:https://www.cnblogs.com/rollenholt/p/2263726.html
Copyright © 2011-2022 走看看