优雅的写出python代码

打印index(多用enumerate)
bad code

>>> cities = ['Shanghai','Beijing','Shenzhen','Chengdu']
>>> i = 0
>>> for c in cities:
    print (i+1,'-->',c)
    i += 1


1 --> Shanghai
2 --> Beijing
3 --> Shenzhen
4 --> Chengdu

good code

>>> for i,city in enumerate(cities):
    print (i+1,'-->',city)


1 --> Shanghai
2 --> Beijing
3 --> Shenzhen
4 --> Chengdu

两个序列的循环(用zip轻松搞定)
bad code

>>> names = ['leo','jack','john','james']
>>> colors = ['red','green','blue','yellow']
>>> n = min(len(names),len(colors))
>>> for i in range(n):
    print(names[i],'-->',colors[i])


leo --> red
jack --> green
john --> blue
james --> yellow

good code

>>> for name,color in zip(names,colors):
    print ( name,'-->',color)


leo --> red
jack --> green
john --> blue
james --> yellow

交换变量
bad code

>>> x = 1
>>> y = 2
>>> print('>>Before:x={},y={}'.format(x,y))
>>Before:x=1,y=2
>>> tmp = y
>>> y= x
>>> x =tmp
>>> print ('>>After:x={},y={}'.format(x,y))
>>After:x=2,y=1

good code

>>> x,y=y,x
>>> print ('After:x={},y={}'.format(x,y))
After:x=1,y=2

字典的读取
bad code

>>>students={'LiLi':18,'Sam':25}
>>>if 'Susan' in students:
>>> student = students['Susan']
>>>else:
>>> student = 'unknow'
>>>print ('Susan is {} years old'.format(student))
>>>
Susan is unknow years old

good code

>>> student = students.get('Susan','unknow')
>>> print('Susan is {} years old'.format(student))
Susan is unknow years old

循环查找
bad code

target_letter='d'
letters=['a','b','c']
found=False
for letter in letters:
    if letter == target_letter:
        print ('Found')
        found = True
        break
if not found:
    print('Not found')
>>>Not found

good code

target_letter='d'
letters=['a','b','c']
for letter in letters:
    if letter == target_letter:
        print ('Found')
        break
else:
    print('Not found')

>>> Not found

文件读取查找
bad code

f = open('C:/Users/Administrator/Desktop/data.txt')
try:
    text =  f.read()
    for line in text.split('\n'):
        print(line)
finally:
    f.close()

good code

with open('C:/Users/Administrator/Desktop\data.txt') as f:
    for line in f:
        print(line.strip('\n'))

关于锁的写法
bad code

import threading
lock = threading.Lock()
lock.acquire()
try:
    print('Citical part,do something...')
finally:
    lock.release()
>>>Citical part,do something...

good code

import threading
lock = threading.Lock()
with lock:
    print('Citical part,do something...')
>>>Citical part,do something...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值