Python 常用技巧

一些合适的技巧能够帮助代码的可读性更好、性能更高。


# 多行字符串
a = (
        "sele sd "
        "shgg sd"
        "ssss, aaa"
    )
print(a)
# sele sd shgg sdssss, aaa


# if 语句
if i in {1,2,3,4}:
	pass


# 枚举
class Shapes:
	A,B,C,D=range(4)

print(Shapes.A)

# 找出列表中出现最频繁的数
test=[1,2,3,4,3,2,3,4,5,3,2,3,4,5,3,4]
print(max(set(test),key=test.count))
# 3



# 删除list里面的重复元素
lists = [8, 4, 6, 2, 6, 8, 'd', 1, 'b', 2, 4, 6, 'd', 'a', 'c']

# 第一种方法(不保留顺序)
list(set(lists))  # [1, 2, 'c', 4, 6, 8, 'b', 'd', 'a']

# 第二种方法(保留顺序)
li = dict.fromkeys(lists)
list(li.keys())   # [8, 4, 6, 2, 'd', 1, 'b', 'a', 'c']


#  获取两个set 的交集、并集、差集
a = {1, 2, 3, 4, 5}
b = {3, 4, 5, 6, 7}

a.intersection(b)   # 交集 {3, 4, 5}

a.union(b)  # 并集 {1, 2, 3, 4, 5, 6, 7}

a.difference(b) # 差集:a 中有而 b 中没有的  {1, 2}

a.symmetric_difference(b)  # a 和 b 中不重复的元素(a有b没有,或b有a没有)


# 搜索字符串的多个前后缀
print('http://www.google.com'.startswith(('http://','https://')))
# True
print('http://www.google.com'.endswith(('.cn','.com')))
# True


# 不使用循环构造一个列表
import itertools
test=[[1,2],[3,4],[5,6]]
list(itertools.chain.from_iterable(test))
# [1, 2, 3, 4, 5, 6]

# 重置递归限制
import sys
sys.setrecursionlimit(1200)
print(sys.getrecursionlimit())
# 1200

# 递归把嵌套列表解开为一维列表
test = [1,[2,3,[4,5,6,[7,8,9,10],11],12,14],16,17,[18]]
unlock = lambda s: sum(map(unlock,s),[]) if isinstance(s,(list,tuple)) else [s]
print(unlock(test))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 17, 18]


# 使用字典模拟模拟构造一个 switch-case
def switch(x):
	return switch._system_dict.get(x,'不存在')


switch._system_dict = {'folder':'D:\\','file': 'a.txt'}
print(switch('a'))
# 不存在
print(switch('file'))
# a.txt


# 一行代码打印9*9乘法表
print('\n'.join('\t'.join(["%s*%s=%s"%(x,y,x*y) for y in range(1,x+1)]) for x in range(1,10)))
"""
1*1=1
2*1=2   2*2=4
3*1=3   3*2=6   3*3=9
4*1=4   4*2=8   4*3=12  4*4=16
5*1=5   5*2=10  5*3=15  5*4=20  5*5=25
6*1=6   6*2=12  6*3=18  6*4=24  6*5=30  6*6=36
7*1=7   7*2=14  7*3=21  7*4=28  7*5=35  7*6=42  7*7=49
8*1=8   8*2=16  8*3=24  8*4=32  8*5=40  8*6=48  8*7=56  8*8=64
9*1=9   9*2=18  9*3=27  9*4=36  9*5=45  9*6=54  9*7=63  9*8=72  9*9=81
"""


# 娱乐一下,输出心形文字
print('\n'.join([''.join([('但愿人长久'[(x-y)%5] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else',')for x in range(-30,30)])for y in range(15,-15,-1)]))
"""
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,久但愿人长久但愿人,,,,,,,,,,,久但愿人长久但愿人,,,,,,,,,,,,,,,
,,,,,,,,,,,,愿人长久但愿人长久但愿人长久但愿人,,,愿人长久但愿人长久但愿人长久但愿人,,,,,,,,,,,
,,,,,,,,,,但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但,,,,,,,,,
,,,,,,,,,但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人,,,,,,,,
,,,,,,,,但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久,,,,,,,
,,,,,,,,愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但,,,,,,,
,,,,,,,,人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿,,,,,,,
,,,,,,,,长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人,,,,,,,
,,,,,,,,久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长,,,,,,,
,,,,,,,,但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久,,,,,,,
,,,,,,,,,人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久,,,,,,,,
,,,,,,,,,,久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久,,,,,,,,,
,,,,,,,,,,但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但,,,,,,,,,
,,,,,,,,,,,,长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久,,,,,,,,,,,
,,,,,,,,,,,,,但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久,,,,,,,,,,,,
,,,,,,,,,,,,,,人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,但愿人长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人长,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,长久但愿人长久但愿人长久但愿人长久但愿人长久但愿人,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,愿人长久但愿人长久但愿人长久但愿人长久但愿,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,但愿人长久但愿人长久但愿人长久,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,久但愿人长久但愿人,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,长久但,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,但,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
"""


# 有放回随机采样和无放回随机采样
import random
d = [1,2,3,4,5,6]
random.choices(d, k=3)  # 长度为k的list,有放回采样,k可大于d的长度
# [2, 6, 2]
random.sample(d, k=3)   # 长度为k的list,无放回采样,k不可大于d的长度
# [1, 5, 6]


# 字符串搜索
str = '123456'
str.find('7')    # 如果找不到返回-1
# -1
str.index('7')   # 如果找不到抛出ValueError异常
# ValueError: substring not found

# 迭代器工具
import itertools
list(itertools.islice('ABCDEF', 1, 5, None))
# ['B', 'C', 'D', 'E']

list(itertools.filterfalse(lambda x: x < 4, [1, 2, 3, 4, 5]))  # 过滤掉小于4的
# [4, 5]

list(itertools.takewhile(lambda x: x < 4, [1, 2, 4, 3, 5]))  # 当不满足条件x<4时停止迭代
# [1, 2]

list(itertools.dropwhile(lambda x: x < 4, [1, 2, 5, 4, 3]))  # 当不满足条件x<4时开始迭代
# [5, 4, 3]

list(itertools.compress('ABCDEF', [0, 0, 0, 1, 1, 1]))  # 根据True或False进行选择
['D', 'E', 'F']

list(itertools.groupby(sorted([1, 2, 3, 3, 2])))  # 分组排序
"""[(1, <itertools._grouper at 0x1c0baf41cf8>),
 (2, <itertools._grouper at 0x1c0baf41ac8>),
 (3, <itertools._grouper at 0x1c0baf41c18>)]"""

list(itertools.permutations('ABC', 2))  # 排列
# [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]

list(itertools.combinations('ABC', 2))  # 组合
# [('A', 'B'), ('A', 'C'), ('B', 'C')]

list(itertools.chain(['AB'],'CD','E'))   # 多个序列拼接
# ['AB', 'C', 'D', 'E']

注:此代码只是个人根据当时的环境满足了当时的需求,记录下来用做后续参考!如有问题,请检查软硬件环境是否一致,由于时间精力有限,大部分未做详细环境描述。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值