標籤:

Python built-in functions F&G

承接Python built-in functions D&E,繼續探索python的內置函數。

26. file(name[, mode[, buffering]])

Constructor function for the file type, described further in section File Objects. The constructor』s arguments are the same as those of the open() built-in function described below.

When opening a file, it』s preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing isinstance(f, file)).

file可以用來打開文件,和open的用法一樣,但是並不推薦這樣用。

27. filter(function, iterable)

Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable 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 iterable that are false are removed.

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.

See itertools.ifilter() and itertools.ifilterfalse() for iterator versions of this function, including a variation that filters for elements where the function returns false.

Python經典的內置函數,和map,reduce作用方式類似,filter經常用於可迭代對象。filter起到過濾的作用,它利用function函數對迭代對象的每個值進行運算,新建一個列表(如果迭代對象是字元或者tuple那就保留原有類型),該列表的值為運算後結果為TRUE的元素(類似於列表生成式[item for item in iterable if function(item)])。如果function為None,將以元素值作為運算結果值進行filter(類似於列表生成式[item for item in iterable if item])。itertools庫中的ifilter,ifilterfalse有著類似的作用。

Talk is short, show you the code.

>>> l2=filter(None,l1)>>> l2[1, 2, 3, 4, 5]>>> l1=[0,1,2,3,4,5]>>> id(l1)75023688L>>> l2=filter(None,l1)>>> l2[1, 2, 3, 4, 5]>>> id(l2)74920008L>>> l3=filter(lambda x:x/2==1,l1)>>> l3[2, 3]>>> id(l3)75023304L>>> itertools.ifilter(None,l1)<itertools.ifilter object at 0x0000000004795E80>>>> list(itertools.ifilter(None,l1))[1, 2, 3, 4, 5]>>> list(itertools.ifilterfalse(None,l1))[0]>>>

28. class float([x])

Return a floating point number constructed from a number or string x.

If the argument is a string, it must contain a possibly signed decimal or floating point number, possibly embedded in whitespace. The argument may also be [+|-]nan or [+|-]inf. 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. Float accepts the strings nan, inf and -inf for NaN and positive or negative infinity. The case and a leading + are ignored as well as a leading - is ignored for NaN. Float always represents NaN and infinity as nan, inf or -inf. The float type is described in Numeric Types — int, float, long, complex.

浮點數類,不談了。 記住float()可以傳入inf和nan就可以了。

29. format(value[, format_spec])

Convert a value to a 「formatted」 representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument, however there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.

很好用的字元串格式化的方法,它通過{}替代%,有著比%格式化方法更加靈活的應用。它有著幾種基本用法: show you the code

#位置映射>>> {0},{1},{0}.format(Tim,Duncn)Tim,Duncn,Tim>>>#關鍵字參數映射>>> team=Warriors>>> player=Stephen Curry>>> {t} {p}.format(t=team,p=player)Warriors Stephen Curry>>>#對象屬性映射>>> class player():... def __init__(self,team,name):... self.team=team... self.name=name... def __str__(self):... return I am {self.name}, I play in {self.team}!.format(self=self)...>>> str(player(Thunder,Westbrook))I am Westbrook, I play in Thunder!#下標映射>>> player=[Kobe,Bryant]>>>> {p[0]} {p[1]}.format(p=player)Kobe Bryant#填充與對齊#^、<、>分別是居中、左對齊、右對齊,後面帶寬度#:號後面帶填充的字元,只能是一個字元,不指定的話默認是用空格填充>>> {:^10}.format(Paul) Paul >>> {:*<10}.format(Paul)Paul******>>> {:->10}.format(Paul)------Paul>>> {:-->10}.format(Paul)Traceback (most recent call last): File "", line 1, in ValueError: Invalid conversion specification>>>#精度>>> {:.2f}.format(123.456)123.46>>> {:1.2f}.format(123.456)123.46>>> {:6f}.format(123.456)123.456000>>> {:.6f}.format(123.456)123.456000>>> {:6f}.format(123)123.000000#特殊類型,例如多進位,,b、d、o、x分別是二進位、十進位、八進位、十六進位。>>> {:b}.format(12)1100>>> {:d}.format(12)12>>> {:x}.format(12)c>>> {:o}.format(12)14>>>#還可以用作千位分隔符>>> {:,}.format(123456789)123,456,789

30. class frozenset([iterable])

Return a new frozenset object, optionally with elements taken from iterable. frozenset is a built-in class. See frozenset and Set Types — set, frozenset for documentation about this class.

For other containers see the built-in set, list, tuple, and dict classes, as well as the collections module.

一種特殊的set類型,Build an immutable unordered collection of unique elements,一個不可變的集合。它是不可變的,存在哈希值,好處是它可以作為字典的key,也可以作為其它集合的元素。缺點是一旦創建便不能更改,沒有add,remove方法。

31. globals()

Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

該函數會以字典的方式返回當前的所有global變數。與之對應的還有放回局部變數的函數locals()。locals() 返回是當前局部變數的深拷貝,修改locals() 中變數值的時候,實際上對於原變數本身是沒有任何影響的。而globals()返回的是全局變數的字典,修改其中的內容,值會真正的發生改變。

推薦閱讀:

空間數據可視化筆記——simple features空間對象基礎
Kivy中文編程指南:圖形
Python-Numpy模塊Meshgrid函數
為什麼寫的爬蟲只能爬取一幅圖,而不能全部下載所有圖片?

TAG:Python |