Python Tips

Python Tips

Python 小技巧

打印 index

对列表,数列打印他们的 index

  • 一般方法
1
2
3
4
5
cities = ['Shanghai','beijing','Chengdu']
i = 0
for c in cities:
print(i +1,'-->',c)
i += 1
  • 更好的方法(使用 enumerate)
1
2
3
cities = ['Shanghai','beijing','Chengdu']
for i,city in enumerate(cities):
print(i+1,'-->',city)

两个系列循环

对两个序列进行计算或处理

  • 一般方法
1
2
3
4
5
names = ['leo','jack','james']
colors = ['red','green','blue','yellow']
n = min(len(names),len(colors))
for i in range(n):
print(names[i],'-->',colors[i])
  • 更好的方法(使用 zip)
1
2
3
4
names = ['leo','jack','james']
colors = ['red','green','blue','yellow']
for name,color in zip(names,colors):
print(name,'-->',color)

交换变量

多个变量之间的交换,如冒泡排序法

  • 一般方法
1
2
3
4
5
6
7
x = 1
y = 2
print('>>Before:x={},y={}'.format(x,y))
tmp = y
y = x
x = tmp
print('>>After:x = {},y = {}'.format(x,y))
  • 更好的方法
1
2
3
4
5
x = 1
y= 2
print('Before:x = {},y = {}'.format(x,y))
x,y = y,x
print('After:x = {},y = {}'.format(x,y))

字典的读取

对字典的访问和读取,读取的字典 key 为空,需要一个缺省值

  • 一般方法
1
2
3
4
5
6
students = {'Lili':18,'Sam':25}
if 'Susan' in students:
student = students['Susan']
else:
student = 'unknow'
print('Susan is {} yesrs old'.format(student))
  • 更好的方法
1
2
3
students = {'Lili':18,'San':25}
student = students.get('Susan','unknow')
print('Susan is {} yesrs'.format(student))
  • 巧妙地利用字典的 get 的方法。若字典没有 Susan 的 key,则用 unknow 来表示缺省值。

循环查找

在一个大的循环中作搜索,如在文件中搜索关键字,从文件名列表中查找特殊的文件名

  • 一般方法
1
2
3
4
5
6
7
8
9
10
11
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')
  • 更好的方法
1
2
3
4
5
6
7
8
9
target_letter = 'd'
letters = ['a','b','c']

for letter in letters:
if letter == target_letter:
print('found')
break
else:
print('Not Found')

文件读取查找

打开以文件,对内容进行循环读取处理

  • 一般方法
1
2
3
4
5
6
7
f = open('data.txt')
try:
text = f.read()
for line in text.split('\n'):
print(line)
finally:
f.close()
  • 更好的方法
1
2
3
with open('data.txt') as f:
for line in f:
print(line.strip('\n'))

关于锁的写法

对于并发操作尤其是多线程的操作,对同一内存进行读写操作时,加锁保护

  • 一般方法
1
2
3
4
5
6
7
8
import threading

lock = threading.Lock()
lock.acquire()
try:
print('Citical par,do somethins...')
finally:
lock.release()
  • 更好的方法
1
2
3
4
import threading
lock = threading.Lock()
with lock:
print('Citical par,do somethins...')

Via


评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×