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(" ","")

 

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