python: built-in method
chunliny
|
1#
chunliny 发表于 2008-09-26 21:35
python: built-in method1. filter(function, list)Construct a list from those elements of list for which function returns true. list may be either a sequence, a container which supports iteration, or an iterator, If list is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of list that are false (zero or empty) are removed. Note that filter(function, list) is equivalent to [item for item in list if function(item)] if function is not None and [item for item in list if item] if function is None. >>> filter(lambda L : L > 10, [1,2,56,14,9]) [56, 14] >>> filter(, [0,1,]) SyntaxError: invalid syntax >>> filter(None, [1,0]) [1] >>> 2. map(function, list, ...)Apply function to every item of list and return a list of the results. If additional list arguments are passed, function must take that many arguments and is applied to the items of all lists in parallel; if a list 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 list arguments, map() returns a list consisting of tuples containing the corresponding items from all lists (a kind of transpose operation). The list arguments may be any kind of sequence; the result is always a list. >>> map(lambda l:l*2,[12,23,34]) [24, 46, 68] 3. reduce(function, sequence[, initializer])Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence 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 sequence. If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If initializer is not given and sequence contains only one item, the first item is returned. >>> reduce(lambda x,y: x+y, [1,2,3,4,5]) 15 4. 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. >>> chr(97)'a'>>> chr(300)Traceback (most recent call last): File "", line 1, in module> chr(300)ValueError: chr() arg not in range(256) ord(c)Return the ASCII value of a string of one character or a Unicode character. E.g., ord('a') returns the integer 97, ord(u'\u2020') returns 8224. This is the inverse of chr() for strings and of unichr() for Unicode characters. >>> ord('a') 97 >>> ord(u'\u2020') 8224 5.int([x[, radix]])Convert a string or number to a plain integer. If the argument is a string, it must contain a possibly signed decimal number representable as a Python integer, possibly embedded in whitespace. The radix parameter gives the base for the conversion and may be any integer in the range [2, 36], or zero. If radix is zero, the proper radix is guessed based on the contents of string; the interpretation is the same as for integer literals. If radix is specified and x is not a string, TypeError is raised. Otherwise, the argument may be a plain or long integer or a floating point number. Conversion of floating point numbers to integers truncates (towards zero). If the argument is outside the integer range a long object will be returned instead. If no arguments are given, returns 0. long([x[, radix]])Convert a string or number to a long integer. If the argument is a string, it must contain a possibly signed number of arbitrary size, possibly embedded in whitespace. The radix argument is interpreted in the same way as for int(), and may only be given when x is a string. Otherwise, the argument may be a plain or long integer or a floating point number, and a long integer with the same value is returned. Conversion of floating point numbers to integers truncates (towards zero). If no arguments are given, returns 0L. float([x])Convert a string or a number to floating point. If the argument is a string, it must contain a possibly signed decimal or floating point number, possibly embedded in whitespace. Otherwise, the argument may be a plain or long integer or a floating point number, and a floating point number with the same value (within Python's floating point precision) is returned. If no argument is given, returns 0.0.Note: When passing in a string, values for NaN and Infinity may be returned, depending on the underlying C library. The specific set of strings accepted which cause these values to be returned depends entirely on the C library and is known to vary. >>> int('-100') -100 >>> long('67890') 67890L >>> float('-30.5') -30.5 6.hex(x)Convert an integer number (of any size) to a hexadecimal string. The result is a valid Python expression. Changed in version 2.4: Formerly only returned an unsigned literal.. oct(x)Convert an integer number (of any size) to an octal string. The result is a valid Python expression. Changed in version 2.4: Formerly only returned an unsigned literal.. >>> hex(32) '0x20' >>> oct(21) '025' 7.raw_input([prompt])If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:>>> s = raw_input('-->')-->12345>>> s'12345' If the readline module was loaded, then raw_input() will use it to provide elaborate line editing and history features. input([prompt])Equivalent to eval(raw_input(prompt)). Warning: This function is not safe from user errors! It expects a valid Python expression as input; if the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation. (On the other hand, sometimes this is exactly what you need when writing a quick script for expert use.)If the readline module was loaded, then input() will use it to provide elaborate line editing and history features. Consider using the raw_input() function for general input from users. >>> s = raw_input('-->') -->1+2 >>> s '1+2' >>> s = input('-->') -->1+2 >>> s 3 8. enumerate(iterable)Return an enumerate object. iterable 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 zero) and the corresponding value obtained from iterating over iterable. enumerate() is useful for obtaining an indexed series: (0, seq[0]), (1, seq[1]), (2, seq[2]), .... New in version 2.3. >>> l=['yang','chun','lin'] >>> t = enumerate(l) >>> t.next() (0, 'yang') >>> t.next() (1, 'chun') >>> t.next() (2, 'lin') >>> >>> for i in enumerate(l): print i (0, 'yang') (1, 'chun') (2, 'lin') 9. 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 unicode. isinstance(obj, basestring) is equivalent to isinstance(obj, (str, unicode)). New in version 2.3. >>> isinstance("yang", basestring) True >>> isinstance(u"\u2020", basestring) True 10. isinstance(object, classinfo)Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof. Also return true if classinfo is a type object and object is an object of that type. If object is not a class instance or an object of the given type, the function always returns false. If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects, or may recursively contain other such tuples (other sequence types are not accepted). If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised. Changed in version 2.2: Support for a tuple of type information was added.>>> isinstance("yang", str)True>>> isinstance(12, int)True>>> isinstance(12,str)False issubclass(class, classinfo)Return true if class is a subclass (direct or indirect) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects, in which case every entry inclassinfo will be checked. In any other case, a TypeError exception is raised. Changed in version 2.3: Support for a tuple of type information was added.>>> issubclass(str, basestring) True 11. zip([seq1, ...])This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple argument sequences 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. 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.. >>> zip([1,2,3,4,5], ['yang','chun','lin']) [(1, 'yang'), (2, 'chun'), (3, 'lin')] 12. vars([object])Without arguments, return a dictionary corresponding to the current local symbol table. With a module, class or class instance object as argument (or anything else that has a __dict__ attribute), returns a dictionary corresponding to the object's symbol table. The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined.>>> class test: def __init__(self): self.x = 1 self.y = 2 def get_x(self): return self.x def get_y(self): return self.y >>> vars(test) {'__module__': '__main__', 'get_x': function get_x at 0x00FFEF70>, 'get_y': function get_y at 0x00FFEFB0>, '__init__': function __init__ at 0x00FFEF30>, '__doc__': None} >>> tt = test() >>> vars(tt) {'y': 2, 'x': 1} >>> test.__dict__ {'__module__': '__main__', 'get_x': function get_x at 0x00FFEF70>, 'get_y': function get_y at 0x00FFEFB0>, '__init__': function __init__ at 0x00FFEF30>, '__doc__': None} >>> tt.__dict__ {'y': 2, 'x': 1} |