今天總結一下在python中常用的一些風格程式碼,這些可能大家都會用,但有時可能也會忘記,在這裡總結,工大家參考~~~
先點贊在看,養成習慣~~~
for i in xrange(6):
print i ** 2
xrange會返回一個迭代器,用來一次一個值地遍歷一個範圍,這種方式比range更省記憶體。在python3中xrange已經改名為range。
colors = ['red', 'green', 'blue', 'yellow']
for color in colors:
print color
for color in reversed(colors):
print color
for i, color in enumerate(colors):
print i, '-->', color
names = ['raymond', 'rachel', 'mattthew']
colors = ['red', 'green', 'blue', 'yellow']
for name, color in izip(names, colors):
print name, '-->', color
zip在記憶體中生成一個新的列表,需要更多的記憶體,izip比zip效率更高。在python3中,izip改名為zip,替換了原來的zip成為內建函數。
colors = ['red', 'green', 'blue', 'yellow']
for color in sorted(colors):
print color
for color in sorted(coloes, reverse = True):
print color
colors = ['red', 'green', 'blue', 'yellow']
print sorted(colors, key=len)
print sum(i ** 2 for i in xrange(10))
def find(seq, target):
for i, value in enumerate(seq):
if value == target:
break
else:
return -1
return i
with open('help.txt', 'w') as f:
with redirect_stdout(f):
help(pow)
上述程式碼用於演示如何臨時把標準輸出重定向到一個檔案,然後再恢復正常。注意redirect_stdout在python3.4加入。
with open('data.txt') as f:
data = f.read()
lock = threading.Lock()
with lock:
print 'critical section 1'
print 'critical section 2'
colors = ['red', 'green', 'red', 'blue', 'green', 'red']
d = {}
for color in colors:
d[color] = d.get(color, 0) + 1
d = defaultdict(int)
for color in colors:
d[color] += 1