python優雅編程之旅

偶然的機會坐上了python的賊船,無奈只能一步步踏上王者之巔。。。。。python

參考博客地址:https://mp.weixin.qq.com/s/OZVT3iFrpFReqdYqVhUf6gapp

1.交換賦值ide

 

##不推薦
temp = a
a = b
b = a  

##推薦
a, b = b, a     #先生成一個元組(tuple)對象,而後unpack
View Code

 

2.uppackui

 

##不推薦
l = ['David', 'Pythonista', '+1-514-555-1234']
first_name = l[0]
last_name = l[1]
phone_number = l[2]  

##推薦
l = ['David', 'Pythonista', '+1-514-555-1234']
first_name, last_name, phone_number = l
View Code

 

3.使用操做符 in 判斷spa

 

#不推薦
if fruit == "apple" or fruit == "orange" or fruit == "berry":
    # 屢次判斷  

##推薦
if fruit in ["apple", "orange", "berry"]:
    # 使用 in 更加簡潔
View Code

 

4.字符串操做code

 

##不推薦
colors = ['red', 'blue', 'green', 'yellow']

result = ''
for s in colors:
    result += s  #  每次賦值都丟棄之前的字符串對象, 生成一個新對象  

##推薦
colors = ['red', 'blue', 'green', 'yellow']
result = ''.join(colors)  #  沒有額外的內存分配
View Code

 

join用法 :用於將序列中的元素以指定的字符鏈接生成一個新的字符串。對象

str = "-";
seq = ("a", "b", "c"); # 字符串序列
print str.join( seq );

結果:a-b-c

5.字典鍵值列表blog

 

my_dict = {1:'a',2:'b'}
##不推薦
for key in my_dict.keys():
    print(my_dict[key])

##推薦
for key in my_dict:
    print(my_dict[key])

# 只有當循環中須要更改key值的狀況下,咱們須要使用 my_dict.keys()
# 生成靜態的鍵值列表。


結果:a b
      a b
View Code

 

6.字典鍵值判斷內存

 

my_dict = {1:'a',2:'b'}

key = 1

##推薦
if key in my_dict:
    print('True')

#另外一種方法,效率不知
if my_dict.get(key):
    print('True')
View Code

 

7.字符串

相關文章
相關標籤/搜索