1. 程式人生 > >這函式誰總結的啊?這也太屌了吧!Python函式五分鐘學會!

這函式誰總結的啊?這也太屌了吧!Python函式五分鐘學會!

all(iterable)

如果可迭代的物件(陣列,字串,列表等,下同)中的元素都是 true (或者為空)的話返回 True 。

給大家整理了Python很全面的資料和教程可以下載,加群943752371即可

_all = True

for item in iterable:

if not item:

_all = False

break

if _all:

# do stuff

更簡便的寫法是:

if all(iterable):

# do stuff

any(iterable)

如果可迭代的物件中任何一個元素為 true 的話返回 True 。如果可迭代的物件為空則返回 False 。

_any = False

for item in iterable:

if item:

_any = True

break

if _any:

# do stuff

更簡便的寫法是:

if any(iterable):

# do stuff

cmp(x, y)

比較兩個物件 x 和 y 。 x < y 的時候返回負數, x ==y 的時候返回 0, x > y 的時候返回正數。

def compare(x,y):

if x < y:

return -1

elif x == y:

return 0

else:

return 1

你完全可以使用一句 cmp(x, y) 來替代。

dict([arg])

使用 arg 提供的條目生成一個新的字典。

arg 通常是未知的,但是它很方便!比如說,如果我們想把一個含兩個元組的列表轉換成一個字典,我們可以這麼做。

l = [('Knights', 'Ni'), ('Monty', 'Python'), ('SPAM', 'SPAAAM')]

d = dict()

for tuple in l:

d[tuple[0]] = tuple[1]

# {'Knights': 'Ni', 'Monty': 'Python', 'SPAM': 'SPAAAM'}

或者這樣:

l = [('Knights', 'Ni'), ('Monty', 'Python'), ('SPAM', 'SPAAAM')]

d = dict(l) # {'Knights': 'Ni', 'Monty': 'Python', 'SPAM': 'SPAAAM'}

enumerate(iterable [,start=0])

我真的是超級喜歡這個!如果你以前寫過 C 語言,那麼你可能會這麼寫:

for i in range(len(list)):

# do stuff with list[i], for example, print it

print i, list[i]

噢,不用那麼麻煩!你可以使用 enumerate() 來提高可讀性。

for i, item in enumerate(list):

# so stuff with item, for example print it

print i, item

isinstance(object, classinfo)

如果 object 引數是 classinfo 引數的一個例項或者子類(直接或者間接)的話返回 True 。

當你想檢驗一個物件的型別的時候,第一個想到的應該是使用 type() 函式。

if type(obj) == type(dict):

# do stuff

elif type(obj) == type(list):

# do other stuff

...

或者你可以這麼寫:

if isinstance(obj, dict):

# do stuff

elif isinstance(obj, list):

# do other stuff

...

pow(x, y [,z])

返回 x 的 y 次冪(如果 z 存在的話則以 z 為模)。

如果你想計算 x 的 y 次方,以 z 為模,那麼你可以這麼寫:

mod = (x ** y) % z

但是當 x=1234567, y=4567676, z=56 的時候我的電腦足足跑了 64 秒!

不要用 ** 和 % 了,使用 pow(x, y, z) 吧!這個例子可以寫成 pow(1234567, 4567676, 56) ,只用了 0.034 秒就出了結果!

zip([iterable, ])

這個函式返回一個含元組的列表,具體請看例子。

l1 = ('You gotta', 'the')

l2 = ('love', 'built-in')

out = []

if len(l1) == len(l2):

for i in range(len(l1)):

out.append((l1[i], l2[i]))

# out = [('You gotta', 'love'), ('the', 'built-in)]

或者這麼寫:

l1 = ['You gotta', 'the']

l2 = ['love', 'built-in']

out = zip(l1, l2) # [('You gotta', 'love'), ('the', 'built-in)]

如果你想得到倒序的話加上 * 操作符就可以了。

print zip(*out)

# [('You gotta', 'the'), ('love', 'built-in')]

結論

Python 內建函式很方便,它們很快並且經過了優化,所以它們可能效率更高。

我真心認為每個 Python 開發者都應該好好看看內建函式的文件(引言部分)。

忘了說了,在 itertools 模組中有很多很不錯的函式。再說一次,它們確實屌爆了。



作者:919b0c54458f
連結:https://www.jianshu.com/p/ead78e2fd95a
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯絡作者獲得授權並註明出處。