首页 > 编程语言 > 详细

30个python常用小技巧

时间:2021-07-25 23:38:46      阅读:27      评论:0      收藏:0      [点我收藏+]
def small(a, b, c):
    return a if a<b and a<c else (b if b<a and b<c else c)

print(‘a‘ if 1<2 and 1<3 else(‘b‘ if 1<2 and 1<3 else ‘c‘)) # 为啥都喜欢把结果放在条件判断语句的前面 
# 真的是显人耳目
print(small(1, 0, 1))
print(small(1, 2, 2))
print(small(2, 2, 3))
print(small(5, 4, 3))

# 列表推导
x = [m*2 if m>10 else m*4 for m in range(50)]
print(x)


# 多行字符串

multistr = "select * from multi_row where row_id < 5"
print(multistr)


# 存储列表元素到新的变量

testList = [1, 2, 3]
x, y, z = testList    # 变量个数应该和列表长度严格一致
print(x, y, z)

# 打印引入模板的绝对路劲

import threading
import socket
print(threading)
print(socket)


# 字典/集合推导式

testDic = {i: i * i for i in range(10)}
testSet = {i * 2 for i in range(10)}
print(testDic)
print(testSet)


# 调试脚本 用pdb模块设置断点

# import pdb # 不会用这个调试模块
# pdb.runcall(sum, 1, 2)  


# python -m http.server 开启文件共享 -m表示从根目录

# 检查python中的对象
test = [1, 3, 5, 7]
print(dir(test))
test = range(10)
print(dir(test))


# 检测python脚本
import sys
if not hasattr(sys, "hexversion") or sys.version_info != (2, 7):
    print("sorry, you are not running on python 2.7")
    print("current python version:", sys.version)


# 组合多个字符串


test = ["I", "Like", "Python"]
print(test)
print("".join(test))


# 用枚举在循环中找索引

test = [10, 20, 30]
for i, value in enumerate(test):
    print(i, ‘:‘, value)

# 定义枚举量

class shapes:
    circle, square, triangle, quadrangle = range(4)
print(shapes.circle)
print(shapes.square)
print(shapes.triangle)
print(shapes.quadrangle)


# 从方法中返回多个值

def x():
    return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)


# 运用*运算符unpack函数参数

def test(x, y, z):
    print(x, y, z)
testDic = {‘x‘:1, ‘y‘:2, ‘z‘:3}
testList = [10, 20, 30]
test(*testDic)
test(**testDic)
test(*testList)


# 用字典来存储表达式

stdcalc = {
    "sum": lambda x, y: x + y,
    "subtract": lambda x, y: x - y
}
print(stdcalc["sum"](9, 3))
print(stdcalc["subtract"](9, 3))


# 计算任何数的阶乘

import functools
result = (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(3)
print(result)

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

# 重置递归次数,python递归次数只有1000下

import sys
x = 1200
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())


# 检查一个对象的内存使用

import sys
x = 1
print(sys.getsizeof(x))    # python3.5中一个32比特的整数占用28字节


# 使用slots减少内存开支

import sys
# 原始类
class FileSystem(object):
    def __init__(self, files, folders, devices):
        self.files = files
        self.folder = folders
        self.devices = devices
print(sys.getsizeof(FileSystem))
# 减少内存后
class FileSystem(object):
    __slots__ = [‘files‘, ‘folders‘, ‘devices‘]
    def __init__(self, files, folders, devices):
        self.files = files
        self.folder = folders
        self.devices = devices
print(sys.getsizeof(FileSystem))


# 使用lambda模仿输出

import sys
lprint = lambda *args: sys.stdout.write(" ".join(map(str, args)))
lprint("python", "tips", 1000, 1001)

# 两个相关序列构建一个字典

t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict(zip(t1, t2)))

# 搜索字符串的多个前后缀

print("http://localhost:8888/notebooks/Untitled6.ipynb".startswith(("http://", "https://")))
print("http://localhost:8888/notebooks/Untitled6.ipynb".endswith((".ipynb", ".py")))


# 不使用循环构建一个列表

import itertools
import numpy as np
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test)))

# 实现switch-case语句

def xswitch(x):
    return  xswitch._system_dict.get(x, None)
xswitch._system_dict = {"files":10, "folders":5, "devices":2}
print(xswitch("default"))
print(xswitch("devices"))

30个python常用小技巧

原文:https://www.cnblogs.com/wkhzwmr/p/15059128.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!