python :built-in functions

今天研究下python 的 内建函数:



  Built-in Functions    
abs()divmod()input()open()staticmethod()
all()enumerate()int()ord()str()
any()eval()isinstance()pow()sum()
basestring()execfile()issubclass()print()super()
bin()file()iter()property()tuple()
bool()filter()len()range()type()
bytearray()float()list()raw_input()unichr()
callable()format()locals()reduce()unicode()
chr()frozenset()long()reload()vars()
classmethod()getattr()map()repr()xrange()
cmp()globals()max()reversed()zip()
compile()hasattr()memoryview()round()__import__()
complex()hash()min()set() 
delattr()help()next()setattr() 
dict()hex()object()slice() 
dir()id()oct()sorted()


abs():Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned.

绝对值,如果复数的话返回复数的模


all
(iterable)

Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

New in version 2.5.

iterable 都是True(或者为空)的话返回True,否则返回False



any(iterable)

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

New in version 2.5.

如果iterable里面有一个item是True的话返回True



basestring
()

This abstract type is the superclass for str and unicode. It cannot be called or instantiated, but it can be used to test whether an object is an instance of str or unicodeisinstance(obj, basestring) is equivalent to isinstance(obj, (str, unicode)).

New in version 2.3.


bin ( x )

Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

New in version 2.6.

返回x的二进制,可以是负数,但是必须是integer



class bool([x])

Return a Boolean value, i.e. one of True or Falsex is converted using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns Truebool is also a class, which is a subclass of int. Class bool cannot be subclassed further. Its only instances are False and True.

New in version 2.2.1.

Changed in version 2.3: If no argument is given, this function returns False.

判断True还是False,如果bool(),则是False。 它是int的子类并且不能继续被继承,他的例化只能是False或者True




class bytearray([source[encoding[errors]]])

Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the str type has, see String Methods.

The optional source parameter can be used to initialize the array in a few different ways:

  • If it is unicode, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the unicode to bytes using unicode.encode().
  • If it is an integer, the array will have that size and will be initialized with null bytes.
  • If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
  • If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

Without an argument, an array of size 0 is created.

New in version 2.6.

没看懂大哭



callable(object)

Return True if the object argument appears callable, False if not. If this returns true, it is still possible that a call fails, but if it is false, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); class instances are callable if they have a __call__() method.

检查函数是否能被调用,可以调用的返回True,不能调用的返回False



chr ( i )

Return a string of one character whose ASCII code is the integer i. For example, chr(97) returns the string 'a'. This is the inverse of ord(). The argument must be in the range [0..255], inclusive;ValueError will be raised if i is outside that range. See also unichr().

  把integer转成相对应ASCII码的字符,范围在[0..255]之间。反之用ord()



classmethod(function)

Return a class method for function.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C(object):
    @classmethod
    def f(cls, arg1, arg2, ...):
        ...

The @classmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section.

For more information on class methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

New in version 2.2.

Changed in version 2.4: Function decorator syntax added.

目前没看懂大哭




cmp(xy)

Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.

比较大小,没啥可说的。




divmod(ab)

Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using long division. With mixed operand types, the rules for binary arithmetic operators apply. For plain and long integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).

Changed in version 2.3: Using divmod() with complex numbers is deprecated.

取模


enumerate(sequencestart=0)

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence:

>>>
>>> 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')]

Equivalent to:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

New in version 2.3.

Changed in version 2.6: The start parameter was added.

sequence 必须是一个iterator,然后返回一个tuple



range(stop) range(startstop[step])

This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start +i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stopstep must not be zero (or else ValueError is raised). Example:



>>> 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)
[]

产生一个list,stop的数据不包含在内。step是可选,如果只有一个参数,就是stop,start没给默认从零开始。


(xrange参见另一个帖子)


capitalize()首字母大写

str.replace('needtoreplaced_char','replaced') 字符串里面的字符的替换

str.split()字符串切割



len:序列长度
max:序列中最大值
min:最小值
filter:过滤序列


>>> filter(lambda x:x%2==0, [1,2,3,4,5,6])
[2, 4, 6]



zip([iterable...])

This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.

The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).

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

New in version 2.0.

Changed in version 2.4: Formerly, zip() required at least one argument and zip() raised a TypeError instead of returning an empty list.

并行的合并list 变成一个tuple的list,长度(tuple的个数)按照最短那个list来定。并且可以用*号来解包。



map(functioniterable...)

Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map()returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.


当第一个参数function 为 None的时候,map返回并行的多个list的tuple list,长度由最长的决定,短的list(由None type)补齐。

当function有定义的时候,会把后面的参数应用到这个function上来。



reduce(functioniterable[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. Roughly equivalent to:

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        try:
            initializer = next(it)
        except StopIteration:
            raise TypeError('reduce() of empty sequence with no initial value')
    accum_value = initializer
    for x in it:
        accum_value = function(accum_value, x)
    return accum_value
只有一个iterable,把一个iterable算成一个数字

BUG -- Linker flags (Release): -Wl,--gc-sections -Wl,--as-needed -Wl,--no-undefined -- Linker flags (Debug): -Wl,--gc-sections -Wl,--as-needed -Wl,--no-undefined -- ccache: NO -- Precompiled headers: NO -- Extra dependencies: dl m pthread rt -- 3rdparty dependencies: -- -- OpenCV modules: -- To be built: calib3d core dnn features2d flann gapi highgui imgcodecs imgproc ml objdetect photo stitching ts video videoio -- Disabled: world -- Disabled by dependency: - -- Unavailable: java python2 python3 -- Applications: tests perf_tests apps -- Documentation: NO -- Non-free algorithms: NO -- -- GUI: GTK3 -- GTK+: YES (ver 3.24.20) -- GThread : YES (ver 2.64.6) -- GtkGlExt: NO -- VTK support: NO -- -- Media I/O: -- ZLib: /usr/lib/x86_64-linux-gnu/libz.so (ver 1.2.11) -- JPEG: /usr/lib/x86_64-linux-gnu/libjpeg.so (ver 80) -- WEBP: build (ver encoder: 0x020f) -- PNG: /usr/lib/x86_64-linux-gnu/libpng.so (ver 1.6.37) -- TIFF: /usr/lib/x86_64-linux-gnu/libtiff.so (ver / ) -- JPEG 2000: OpenJPEG (ver 2.4.0) -- OpenEXR: /usr/lib/x86_64-linux-gnu/libImath.so /usr/lib/x86_64-linux-gnu/libIlmImf.so /usr/lib/x86_64-linux-gnu/libIex.so /usr/lib/x86_64-linux-gnu/libHalf.so /usr/lib/x86_64-linux-gnu/libIlmThread.so (ver 2_3) -- HDR: YES -- SUNRASTER: YES -- PXM: YES -- PFM: YES -- -- Video I/O: -- DC1394: YES (2.2.5) -- FFMPEG: YES -- avcodec: YES (58.54.100) -- avformat: YES (58.29.100) -- avutil: YES (56.31.100) -- swscale: YES (5.5.100) -- avresample: NO -- GStreamer: YES (1.16.3) -- v4l/v4l2: YES (linux/videodev2.h) -- -- Parallel framework: pthreads -- -- Trace: YES (with Intel ITT) -- -- Other third-party libraries: -- VA: NO -- Lapack: NO -- Eigen: YES (ver 3.3.7) -- Custom HAL: NO -- Protobuf: build (3.19.1) -- -- OpenCL: YES (no extra features) -- Include path: /home/hyzk/Downloads/opencv-4.7.0/3rdparty/include/opencl/1.2 -- Link libraries: Dynamic load -- -- Python (for build): /usr/bin/python3 -- -- Java: -- ant: NO -- JNI: NO -- Java wrappers: NO -- Java tests: NO -- -- Install to: /usr/local
最新发布
07-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值