Python的几个高级编程技巧

我是研究僧i 提交于 2019-11-29 22:36:42

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用于过滤数据

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

统计序列元素的频度和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)])

怎样实现长度为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时如果有数字元素怎么办

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基础、数据分析、大数据、推荐系统知识;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!