打印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...