python优雅编程之旅

偶然的机会坐上了python的贼船,无奈只能一步步踏上王者之巅。。。。。

参考博客地址:https://mp.weixin.qq.com/s/OZVT3iFrpFReqdYqVhUf6g

1.交换赋值

##不推荐
temp = a
a = b
b = a  

##推荐
a, b = b, a     #先生成一个元组(tuple)对象,然后unpack
View Code

2.uppack

##不推荐
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 判断

#不推荐
if fruit == "apple" or fruit == "orange" or fruit == "berry":
    # 多次判断  

##推荐
if fruit in ["apple", "orange", "berry"]:
    # 使用 in 更加简洁
View Code

4.字符串操作

##不推荐
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.字典键值列表

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.

猜你喜欢

转载自www.cnblogs.com/tang-s/p/9749179.html