30个python常用小技巧

下方代码的知识点及技巧

1:三元运算符把结果放在条件判断语句的前面

def small(a, b, c):
    return a if a<b and a<c else (b if b<a and b<c else c)

2:python的传参真的很可 只要参数的数量在传递时对的上

def small(a, b, c):
  pass
print(small(1, 0, 1))

3:字典列表元组集合推导式都可以用这样的形式m for m in range(50),再加上对应所需的括号

print(small(1, 0, 1))

4:\不仅是转义字符还是换行符

# 多行字符串

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

5:print('模块名') # 可以打印出模块的绝对路劲,前提是导入该模块

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)

6:dir(模块名或者对象) # 可以打印出模块或对象中使用的方法

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

7:把列表元组中多个字符串添加在字符串中的方法"".join(test)) #test为列表元组字典对象

# 组合多个字符串
test = ["I", "Like", "Python"]
print(test)
print("".join(test))

8:range()函数可赋值给多个变量circle, square, triangle, quadrangle = range(4)

# 定义枚举量

class shapes:
    
    circle, square, triangle, quadrangle = range(4)
circle, square, triangle, quadrangle = range(4)
print('这个是range函数迭代赋值给对应个数的参数:在下方')
print(circle)
print(shapes.circle)
print(shapes.square)
print(shapes.triangle)
print(shapes.quadrangle)

9:模仿输入# sys.stdout.write

1.默认不换行
2.参数必须是字符串

# 使用lambda模仿输出
import sys
# *args传递一个可变参数列表给函数实参,这个参数列表的数目未知,甚至长度可以为0
# *kwargs则是将一个可变的关键字参数的字典传给函数实参,同样参数列表长度可以为0或为其他值
lprint = lambda *args: sys.stdout.write(" ".join(map(str, args))) # map() 会根据提供的函数对指定序列做映射
# map(function,interable)
# sys.stdout.write
## 1.默认不换行
# 2.参数必须是字符串
lprint("python", "tips", 1000, 1001)

10:map函数可以用任意函数做指定映射输出任意值

map() 会根据提供的函数对指定序列做映射
map(function,interable)

import sys
# *args传递一个可变参数列表给函数实参,这个参数列表的数目未知,甚至长度可以为0
# *kwargs则是将一个可变的关键字参数的字典传给函数实参,同样参数列表长度可以为0或为其他值
lprint = lambda *args: sys.stdout.write(" ".join(map(str, args))) # map() 会根据提供的函数对指定序列做映射
lprint("python", "tips", 1000, 1001)

11:system.getsizeof()检查一个对象的内存使用

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

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

12:使用slots减少内存开支,具体就是__slots__ =["接下来要传的参数值","",""]

# 使用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):
    # 用__sort__对他们的类中函数传进去的参数进去处理
    __slots__ = ['files', 'folders', 'devices']
    def __init__(self, files, folders, devices):
        self.files = files
        self.folder = folders
        self.devices = devices
print(sys.getsizeof(FileSystem))

13:两个相关序列构建一个字典dict(zip(t1, t2)

# 两个相关序列构建一个字典
t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict(zip(t1, t2)))

14:返回True or False 搜索字符串的多个前后缀 检查字符串是否是以指定子字符串开头startswitch,endswith结尾,可以使用元组进行逐一配对

# 搜索字符串的多个前后缀
# 检查字符串是否是以指定子字符串开头startswitch,endswith结尾,可以使用元组进行逐一配对
print("http://localhost:8888/notebooks/Untitled6.ipynb".startswith(("http://", "https://")))
print("http://localhost:8888/notebooks/Untitled6.ipynb".endswith((".ipynb", ".py")))

15:展平嵌套列表

print(list(itertools.chain.from_iterable(test))) # 暂时把他看成个迭代器模块,他会把多个列表变成一个列表

# 不使用循环构建一个列表
import itertools
test = [[-1, -2], [30, 40], [25, 35]]
# 展平嵌套列表
print(list(itertools.chain.from_iterable(test))) # 暂时把他看成个迭代器模块,他会把多个列表变成一个列表

16: 实现switch-case语句

def xswitch(x):
    return  xswitch._system_dict.get(x, None)
    # dict.get(),会返回其对应的key值,否则会返回一个定义的参数d
xswitch._system_dict = {"files":10, "folders":5, "devices":2}
print(xswitch("default"))
print(xswitch("devices"))

全部总的代码


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)) # python的传参真的很可 只要对上数字就可
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)]
{m*2:m 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
import math
print(math)
print(threading)
print(socket)


# 字典/集合推导式

c
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)
circle, square, triangle, quadrangle = range(4)
print('这个是range函数迭代赋值给对应个数的参数:在下方')
print(circle)
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))


# 计算任何数的阶乘

# python的数学计算还是真的多
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字节
# 获取尺寸大小 of

# 使用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):
    # 用__sort__对他们的类中函数传进去的参数进去处理
    __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
# *args传递一个可变参数列表给函数实参,这个参数列表的数目未知,甚至长度可以为0
# *kwargs则是将一个可变的关键字参数的字典传给函数实参,同样参数列表长度可以为0或为其他值
lprint = lambda *args: sys.stdout.write(" ".join(map(str, args))) # map() 会根据提供的函数对指定序列做映射
# map(function,interable)
# sys.stdout.write
## 1.默认不换行
# 2.参数必须是字符串
lprint("python", "tips", 1000, 1001)

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

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

# 搜索字符串的多个前后缀
# 检查字符串是否是以指定子字符串开头startswitch,endswith结尾,可以使用元组进行逐一配对
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)
    # dict.get(),会返回其对应的key值,否则会返回一个定义的参数d
xswitch._system_dict = {"files":10, "folders":5, "devices":2}
print(xswitch("default"))
print(xswitch("devices"))
posted @ 2021-07-25 21:41  索匣  阅读(287)  评论(0编辑  收藏  举报