python技巧

相关技巧学习来源于网上抑或书本,学习源附在最后,内容不定期更新。
使用环境:pyharm+python3.7

文章目录

    • 多个字典的公共key
    • 提升命名可读性
    • 计数

多个字典的公共key

from random import randint,sample
from functools import reduce

# 创建三个随机字典
for num in range(1,4):
    locals()['d'+str(num)] = {k:randint(1,10) for k in sample('abcdefg',randint(3,6))}
common_key = [k for k in d1 if k in d2 and k in d2]

# 将字典装入列表,使用map
d = [d1,d2,d3]
common_key_1 = [k for k in d[0] if all(map(lambda d1:k in d1,d[1:]))]

# 使用reduce,集合取交集
common_key_2 = reduce(lambda a,b:a&b,map(dict.keys,d))
print('common_key:{}\ncommon_key_1:{}\ncommon_key_2:{}'.format(common_key,common_key_1,common_key_2))

提升命名可读性

s = ('Alice',16,'male')
# 使用枚举
from enum import IntEnum

class StudentEnum(IntEnum):
    NAME = 0
    AGE = 1
    SEX = 2

print(s[StudentEnum.NAME])

# 命名元祖
from collections import namedtuple
# 返回一个子类
Student = namedtuple('Student',['name','age','sex','email'])

s = Student(name='Jim',age=16,sex='male',email='[email protected]')

s.name

计数

ls = np.random.randint(5,11,20)
d = dict.fromkeys(ls,0)
for each in ls:
    d[each] += 1
# 取出前三
sorted(((v,k) for k,v in d.items()),reverse=True)[:3]

# 使用堆结构
import heapq
# 取出最大的三个
heapq.nlargest(3,((v,k) for k,v in d.items()))
# 取出最小的三个
heapq.nsmallest(3,((v,k) for k,v in d.items()))


# 使用Counter计数
from collections import Counter
c = Counter(np.random.randint(5,11,20))
# 取出频数最高的三个
c.most_common(3)

学习来源:
https://www.bilibili.com/video/av63348708

你可能感兴趣的:(Python)