|
Posted on 2005-10-11 17:00 任我行 阅读(1513) 评论(0) 编辑 收藏 引用 所属分类: Python
今天继续dive into python.
12、列表与字符串 1)用一个字符串对象的join 方法将列表元素连接成单个字符串,此字符串充当分隔符。 2)join 只用用于字符串列表;它不进行任何的类型强制转换。连接一个存在一个或多个非字符串元素的列表将引发一个异常。 3)用一个字符串对象的split 方法将列表元素连接成单个字符串,此字符串充当分隔符。 4)split 接受一个可选的第二个参数,它是要分割的次数。 5)split 无参数调用时,默认为以空白为分隔符(空格/换行/制表符),多个连续空白初见为一个。
13、导入模块 1)Python用两种方法导入模块,一是import module,一种是from module import, 2)第一种方法导入整个模块,对其属性或方法的引用要加限制名,如: >>> import types >>> types.FunctionType 3)第二种方法将模块的方法和属性直接导入名字空间中,可以直接引用这些方法和属性,如: >>> from types import FunctionType >>> FunctionType 4)两种方法各有利弊,前者可明确指定要导入的方法和属性,并直接引用,比较方便;对于属性或方法重名的情况,则后者非常有用。
14、函数的参数 1)函数的参数可以拥有缺省值,某个参数有什么缺省值在定义函数时指明, 2)拥有缺省值的参数为可选参数,否则为必备参数,即调用函数时必须为必备参数提供参数,如果没有对可选参数提供参数值,则其使用缺省值。 3)调用函数时,可以通过指定参数名而以任意次序来传递参数,称为定名参数。如: 定义: def help(object, spacing=10, collapse=1): 合法调用: help(odbchelper) help(odbchelper, 12) help(odbchelper, collapse=0) help(spacing=15, object=odbchelper) 4)参数是个“字典”,缺省可以不指定名字而用顺序将参数名与值匹配起来。
15、内置函数 1)所有Python内置函数被组合进一个名叫 __builtins__ (前后有两个下划线)的特别模块中。 2)内置函数dir 返回任意一个对象的属性和方法的列表。 3)内置函数str 强制将任一种类型的数据转化为字符串,对python的空值None,则str(None)返回字符串"None”. 4)内置函数type 返回任意对象的数据类型。 5)使用函数 getattr 得到对象的各种引用,这个过程中方法没有被调用。 6)使用getattr得到引用后,其返回值为方法,可以调用相应的函数。如下: >>>getattr(li, "append")("Moe") 16、列表映射过滤语法 [mapping-expression for element in source-list if filter-expression]
17、and-or技巧,对bool and a or b来说, 1)逻辑运行采用了快捷方式,即如果or前值为真,是不再计算后面的值,并返回前面的结果 2)用 (bool and [a] or )[0]的方法,可以实现与c中bool?a:b的功能
18、lambda函数 1)可以使用lambda定义单行的最小函数,格式如下: funcVar = lambda x : x... 没有名字,返回是默认的。上式中可以没有funcVar,有funcVar时可与正常函数一样调用,没有funcVar时可如下调用: (lambda x:x...)(a) 2)lambda函数可以接受一到多个参数(包括可选参数),返回单个表达式的值,函数中不能包含命令,表达式不能超过一个。
19、一些小技巧 1)python几乎总是在操作列表 2)字符串的ljust(spacing)可以在右边加空格以达到spacing值所示的长度,当spacing的值小于字符串的长度时,不会截断。
附:builtin的属性表
属性 |
说明 |
ArithmeticError |
Base class for arithmetic errors.
|
AssertionError |
Assertion failed. |
AttributeError |
Attribute not found. |
DeprecationWarning |
Base class for warnings about deprecated features. |
EOFError |
Read beyond end of file. |
EnvironmentError |
Base class for I/O related errors. |
Exception |
Common base class for all exceptions. |
FloatingPointError |
Floating point operation failed. |
FutureWarning |
Base class for warnings about constructs that will change semantically in the future. |
IOError |
I/O operation failed. |
ImportError |
Import can't find module, or can't find name in module. |
IndentationError |
Improper indentation. |
IndexError |
Sequence index out of range. |
KeyError |
Mapping key not found. |
KeyboardInterrupt |
Program interrupted by user. |
LookupError |
Base class for lookup errors. |
MemoryError |
Out of memory. |
NameError |
Name not found globally. |
NotImplementedError |
Method or function hasn't been implemented yet. |
OSError |
OS system call failed. |
OverflowError |
Result too large to be represented. |
OverflowWarning |
Base class for warnings about numeric overflow. |
PendingDeprecationWarning |
Base class for warnings about features which will be deprecated in the future. |
ReferenceError |
Weak ref proxy used after referent went away. |
RuntimeError |
Unspecified run-time error. |
RuntimeWarning |
Base class for warnings about dubious runtime behavior. |
StandardError |
Base class for all standard Python exceptions. |
StopIteration |
Signal the end from iterator.next(). |
SyntaxError |
Invalid syntax. |
SyntaxWarning |
Base class for warnings about dubious syntax. |
SystemError |
Internal error in the Python interpreter. Please report this to the Python maintainer, along with the traceback, the Python version, and the hardware/OS platform and version. |
SystemExit |
Request to exit from the interpreter. |
TabError |
Improper mixture of spaces and tabs. |
TypeError |
Inappropriate argument type. |
UnboundLocalError |
Local name referenced but not bound to a value. |
UnicodeDecodeError |
Unicode decoding error. |
UnicodeEncodeError |
Unicode encoding error. |
UnicodeError |
Unicode related error. |
UnicodeTranslateError |
Unicode translation error. |
UserWarning |
Base class for warnings generated by user code. |
ValueError |
Inappropriate argument value (of correct type). |
Warning |
Base class for warning categories. |
WindowsError |
MS-Windows OS system call failed. |
ZeroDivisionError |
Second argument to a division or modulo operation was zero. |
builtin方法(函数)表
方法 |
说明 |
__import__ |
__import__(name, globals, locals, fromlist) -> module Import a module. The globals are only used to determine the context; they are not modified. The locals are currently unused. The fromlist should be a list of names to emulate ``from name import ...'', or an empty list to emulate ``import name''. When importing a module from a package, note that __import__('A.B', ...) returns package A when fromlist is empty, but its submodule B when fromlist is not empty. |
abs |
abs(number) -> number Return the absolute value of the argument. |
apply |
apply(object[, args[, kwargs]]) -> value Call a callable object with positional arguments taken from the tuple args, and keyword arguments taken from the optional dictionary kwargs. Note that classes are callable, as are instances with a __call__() method. Deprecated since release 2.3. Instead, use the extended call syntax: function(*args, **keywords). |
callable |
callable(object) -> bool Return whether the object is callable (i.e., some kind of function). Note that classes are callable, as are instances with a __call__() method. |
chr |
chr(i) -> character Return a string of one character with ordinal i; 0 <= i < 256. |
cmp |
cmp(x, y) -> integer Return negative if x<y, zero if x==y, positive if x>y. |
coerce |
coerce(x, y) -> None or (x1, y1) When x and y can be coerced to values of the same type, return a tuple containing the coerced values. When they can't be coerced, return None. |
compile |
compile(source, filename, mode[, flags[, dont_inherit]]) -> code object Compile the source string (a Python module, statement or expression) into a code object that can be executed by the exec statement or eval(). The filename will be used for run-time error messages. The mode must be 'exec' to compile a module, 'single' to compile a single (interactive) statement, or 'eval' to compile an expression. The flags argument, if present, controls which future statements influence the compilation of the code. The dont_inherit argument, if non-zero, stops the compilation inheriting the effects of any future statements in effect in the code calling compile; if absent or zero these statements do influence the compilation, in addition to any features explicitly specified. |
delattr |
delattr(object, name) Delete a named attribute on an object; delattr(x, 'y') is equivalent to ``del x.y''. |
dir |
dir([object]) -> list of strings Return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it: No argument: the names in the current scope. Module object: the module attributes. Type or class object: its attributes, and recursively the attributes of its bases. Otherwise: its attributes, its class's attributes, and recursively the attributes of its class's base classes. |
divmod |
divmod(x, y) -> (div, mod) Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x. |
eval |
eval(source[, globals[, locals]]) -> value Evaluate the source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals and locals are dictionaries, defaulting to the current globals and locals. If only globals is given, locals defaults to it. |
execfile |
execfile(filename[, globals[, locals]]) Read and execute a Python script from a file. The globals and locals are dictionaries, defaulting to the current globals and locals. If only globals is given, locals defaults to it. |
filter |
filter(function or None, sequence) -> list, tuple, or string Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list. |
getattr |
getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. |
globals |
globals() -> dictionary Return the dictionary containing the current scope's global variables. |
hasattr |
hasattr(object, name) -> bool Return whether the object has an attribute with the given name. (This is done by calling getattr(object, name) and catching exceptions.) |
hash |
hash(object) -> integer Return a hash value for the object. Two objects with the same value have the same hash value. The reverse is not necessarily true, but likely. |
hex |
hex(number) -> string Return the hexadecimal representation of an integer or long integer. |
id |
id(object) -> integer Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.) |
input |
input([prompt]) -> value Equivalent to eval(raw_input(prompt)). |
intern |
intern(string) -> string ``Intern'' the given string. This enters the string in the (global) table of interned strings whose purpose is to speed up dictionary lookups. Return the string itself or the previously interned string object with the same value. |
isinstance |
isinstance(object, class-or-type-or-tuple) -> bool Return whether an object is an instance of a class or of a subclass thereof. With a type as second argument, return whether that is the object's type. The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for isinstance(x, A) or isinstance(x, B) or ... (etc.). |
issubclass |
issubclass(C, B) -> bool Return whether class C is a subclass (i.e., a derived class) of class B. When using a tuple as the second argument issubclass(X, (A, B, ...)), is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.). |
iter |
iter(collection) -> iterator iter(callable, sentinel) -> iterator Get an iterator from an object. In the first form, the argument must supply its own iterator, or be a sequence. In the second form, the callable is called until it returns the sentinel. |
len |
len(object) -> integer Return the number of items of a sequence or mapping. |
locals |
locals() -> dictionary Update and return a dictionary containing the current scope's local variables. |
map |
map(function, sequence[, sequence, ...]) -> list Return a list of the results of applying the function to the items of the argument sequence(s). If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting None for missing values when not all sequences have the same length. If the function is None, return a list of the items of the sequence (or a list of tuples if more than one sequence). |
max |
max(sequence) -> value max(a, b, c, ...) -> value With a single sequence argument, return its largest item. With two or more arguments, return the largest argument. |
min |
min(sequence) -> value min(a, b, c, ...) -> value With a single sequence argument, return its smallest item. With two or more arguments, return the smallest argument. |
oct |
oct(number) -> string Return the octal representation of an integer or long integer. |
ord |
ord(c) -> integer Return the integer ordinal of a one-character string. |
pow |
pow(x, y[, z]) -> number With two arguments, equivalent to x**y. With three arguments, equivalent to (x**y) % z, but may be more efficient (e.g. for longs). |
range |
range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. |
raw_input |
raw_input([prompt]) -> string Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading. |
reduce |
reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a 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). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. |
reload |
reload(module) -> module Reload the module. The module must have been successfully imported before. |
repr |
repr(object) -> string Return the canonical string representation of the object. For most object types, eval(repr(object)) == object. |
round |
round(number[, ndigits]) -> floating point number Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Precision may be negative. |
setattr |
setattr(object, name, value) Set a named attribute on an object; setattr(x, 'y', v) is equivalent to ``x.y = v''. |
sum |
sum(sequence, start=0) -> value Returns the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start'. When the sequence is empty, returns start. |
unichr |
unichr(i) -> Unicode character Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. |
vars |
vars([object]) -> dictionary Without arguments, equivalent to locals(). With an argument, equivalent to object.__dict__. |
zip |
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)] Return a list of tuples, where each 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. |
|