Python有一些技巧對你來說是新知識,但是還有一些技巧會讓你的代碼效率大幅提升。
本文總結了一下自己用到的一些Python高級編程技巧,希望對大家有幫助。
列表生成器
a=[1,2,3]
[x*x for x in a if x>1]
[4, 9]
集合生成器
a=[1,2,3]
s = {x*x for x in a if x>1}
s
{4, 9}
type(s)
set
字典生成器
a=[1,2,3]
{str(x):x+1 for x in a if x>1}
{'2': 3, '3': 4}
range
list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list(range(3,10))
[3, 4, 5, 6, 7, 8, 9]
filter用于過濾數(shù)據(jù)
list(filter(lambda x:x%3==0, range(10)))
[0, 3, 6, 9]
collections.namedtuple給列表或者元組命名
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, 22)
p.x
11
p.y
22
random的使用
from random import randint
randint(1,10)
1
統(tǒng)計序列元素的頻度和TOP N
from collections import Counter
c = Counter('aaabbbbccccccddddddeeeeee')
c
Counter({'a': 3, 'b': 4, 'c': 6, 'd': 6, 'e': 6})
c.most_common(3)
[('c', 6), ('d', 6), ('e', 6)]
將字典按value排序
from random import randint
keys = 'abcdefg'
d = {x:randint(90,100) for x in keys}
d
{'a': 90, 'b': 98, 'c': 100, 'd': 97, 'e': 95, 'f': 93, 'g': 92}
d.items()
dict_items([('a', 90), ('b', 98), ('c', 100), ('d', 97), ('e', 95), ('f', 93), ('g', 92)])
sorted(d.items(), key=lambda x : x[1])
[('a', 90), ('g', 92), ('f', 93), ('e', 95), ('d', 97), ('b', 98), ('c', 100)]
獲得多個詞典的key的交集
from random import randint, sample
dd1 = {x:randint(90,100) for x in sample('abcdefghij', 5)}
dd2 = {x:randint(90,100) for x in sample('abcdefghij', 5)}
dd3 = {x:randint(90,100) for x in sample('abcdefghij', 5)}
dd1
{'h': 99, 'f': 94, 'c': 91, 'i': 99, 'b': 95}
dd2
{'b': 95, 'g': 91, 'h': 98, 'f': 100, 'd': 92}
dd3
{'h': 95, 'g': 99, 'a': 100, 'd': 96, 'i': 92}
mp = map(dict.keys, (dd1, dd2, dd3))
list(mp)
[dict_keys(['h', 'f', 'c', 'i', 'b']),
dict_keys(['b', 'g', 'h', 'f', 'd']),
dict_keys(['h', 'g', 'a', 'd', 'i'])]
from functools import reduce
reduce(lambda x,y: x&y, mp)
{'h'}
怎樣讓字典按照插入有序
from collections import OrderedDict
d = OrderedDict()
d['x'] = 1
d['y'] = 2
d['a'] = 2
d['b'] = 2
d
OrderedDict([('x', 1), ('y', 2), ('a', 2), ('b', 2)])
怎樣實現(xiàn)長度為N的隊列功能
from collections import deque
d = deque([], 3)
d.append(1)
d.append(2)
d.append(3)
d.append(4)
d
deque([2, 3, 4])
怎樣同時遍歷多個集合
names = [x for x in 'abcdefg']
ages = [x for x in range(21, 28)]
scores = [randint(90,100) for x in range(7)]
for name,age,score in zip(names, ages, scores):
print(name,age,score)
a 21 95
b 22 99
c 23 94
d 24 95
e 25 100
f 26 96
g 27 95
怎樣串行的遍歷多個集合
lista = (randint(1,10) for x in range(10))
listb = [randint(90,100) for x in range(20)]
from itertools import chain
for x in chain(lista, listb):
print(x, end=',')
5,10,3,1,8,7,6,5,6,8,92,95,91,98,95,93,96,95,94,98,92,90,91,91,99,96,90,100,94,99,
使用多種分隔符替換字符串
s = 'a,b;c/d'
import re
re.sub(r'[,;/]', '-', s)
'a-b-c-d'
字符串的模糊搜索與部分替換
s = 'things happend in 2017-08-09, it is a sunddy'
re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2-\1-\3', s)
'things happend in 08-2017-09, it is a sunddy'
列表JOIN時如果有數(shù)字元素怎么辦
print('\t'.join([str(x) for x in ['a','b',33,4.0,'e']]))
a b 33 4.0 e
如何使用多線程-方法1
from threading import Thread
def func(x):
print(x, x*x*x)
ts = []
for x in range(10):
t = Thread(target=func, args=(x,))
t.start()
ts.append(t)
for t in ts:
t.join()
print('main thread over')
0 0
1 1
2 8
3 27
4 64
5 125
6 216
7 343
8 512
9 729
main thread over
如何使用多線程-方法2
以下的輸出錯亂,是正常的,因為多個線程同時print就錯亂了
from threading import Thread
class MyThread(Thread):
def __init__(self, x):
Thread.__init__(self)
self.x = x
def run(self):
print(self.x, self.x*self.x*self.x)
ts = []
for x in range(10):
t = MyThread(x)
t.start()
ts.append(t)
for t in ts:
t.join()
print('main thread over')
0 0
1 1
2 3 27
8
45 64
6 216
125
7 343
8 512
9 729
main thread over
關注我,學習更多Python基礎、數(shù)據(jù)分析、大數(shù)據(jù)、推薦系統(tǒng)知識;
更多文章、技術交流、商務合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
