python相關常用函數與方法總結

1.數字轉list

a = 12345
a_str = list(str(a))

2.list轉字符串

“”.join(list)

#"X",X可以是任何間隔字符,如空,空格,+,-,等

3.range()

#[0,9]
range(10)
#[start,stop)
range(start,stop,step)

4.bool()

bool(0)輸出False
bool(1)輸出True
#若結果爲 0 則考慮num本身是否爲 0,若不爲 0 返回 9
leetcode258,return num % 9 or 9 * bool(num)

5.遍歷字典dict.items()

for key,value in dict.items():
    print(key,value)

6.enumerate()函數:

for index,item in enumerate(seq):
    print(index,item)

#或者,start默認爲0
for index,item in enumerate(seq,start=1):
    print(index,item)

7.python2與python3中/(除法)的區別

#python2
>>> 1/2
0
>>> 1/2.0
0.5
>>> from __future__ import division
>>> 1/2
0.5
>>> 1//2
0

#python3
>>> 1/2
0.5
>>> 1//2
0
>>> 1/2.0
0.5

8.三元表達式

b = b if a<b else a

9.字符串替換字符

b = b.replace(" ","")

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章