python几个技巧

参考 https://mp.weixin.qq.com/s/gGT8EzPH0_CyhNSciVoxKg
来源于Python大数据分析 ,作者朱卫军

合并两个字典

通过**符号解压字典,并将多个字典传入{}中,实现合并, 如果有重复的键, 以后面的为准, 例如这里的’b’

d1 = {"a": 97, "b":98}
d2 = {"A": 65, "B": 66, 'b': 666}

print({**d1, **d2})
print({**d2, **d1})
{'a': 97, 'b': 666, 'A': 65, 'B': 66}
{'A': 65, 'B': 66, 'b': 98, 'a': 97}

链式比较 是并且的意思

a = 5
print(2 < a < 8)
print(5 == a < 3)
print(5 == a > 3)
True
False
True

检查文件是否存在

from os import path

path.exists("aa.txt")
False
# 这里实际上有tt.xlsx文件
path.exists("tt.xlsx")
True

查找出现次数最多的元素

li = (1, 1, 2, 3, 4, 5, 6, 6, 2, 2, 2)
max(set(li), key=li.count)
2
# 也可以是tuple, 只要有count()这个函数就行
mytuple = (1, 1, 2, 3, 4, 5, 6, 6, 2, 2)
max(set(mytuple), key=mytuple.count)
2

将两个列表转换为字典

# 长度相同
list1 = [1, 2, 3]
list2 = ['one', 'two', 'three']

print(dict(zip(list1, list2)))
print(dict(zip(list2, list1)))
{1: 'one', 2: 'two', 3: 'three'}
{'one': 1, 'two': 2, 'three': 3}
# 长度不同  并不报错
list1 = [1, 2, 3, 4, 5]
list2 = ['one', 'two', 'three']

print(dict(zip(list1, list2)))
print(dict(zip(list2, list1)))
{1: 'one', 2: 'two', 3: 'three'}
{'one': 1, 'two': 2, 'three': 3}
# 有重复项
list1 = [1, 1, 2]
list2 = ['one', 'two', 'three']

print(dict(zip(list1, list2)))
print(dict(zip(list2, list1)))
{1: 'two', 2: 'three'}
{'one': 1, 'two': 1, 'three': 2}

统计字频

from collections import Counter

# 可以使字符串, 也可以是列表
result = Counter('bananagraervsCARTSVCvdrsgzbewgfzrgzhh')
print(result)

# 最多的n个元素和个数
print("most n:", result.most_common(3))
Counter({'a': 4, 'g': 4, 'r': 4, 'z': 3, 'b': 2, 'n': 2, 'e': 2, 'v': 2, 's': 2, 'C': 2, 'h': 2, 'A': 1, 'R': 1, 'T': 1, 'S': 1, 'V': 1, 'd': 1, 'w': 1, 'f': 1})
most n: [('a', 4), ('g', 4), ('r', 4)]
result = Counter([1, 2, 3, 4, 5 ,4, 3, 4, 3, 2, 3, 1, 8])
print(result)

# 最多的n个元素和个数
print("most n:", result.most_common(3))
Counter({3: 4, 4: 3, 1: 2, 2: 2, 5: 1, 8: 1})
most n: [(3, 4), (4, 3), (1, 2)]

变量的内存占用

import sys

num = 2
print(sys.getsizeof(num))

li = [num, num]
print(sys.getsizeof(li))
28
80

链式函数调用

在一行代码中调用多个函数, 就像是Scala语言中的科里化

def add(a, b):
    return a + b


def subtract(a, b):
    return a - b


a, b = 5, 10
print((add if b > a else subtract)(a, b))

a, b = 10, 5
print((add if b > a else subtract)(a, b))
15
5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值