广告
返回顶部
首页 > 资讯 > 后端开发 > Python >30个Python常用小技巧
  • 863
分享到

30个Python常用小技巧

小技巧常用Python 2023-01-31 07:01:15 863人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

1、原地交换两个数字x, y =10, 20print(x, y)y, x = x, yprint(x, y)10 2020 102、链状比较操作符n = 10print(1 < n < 20)print(1 > n &

1、原地交换两个数字
x, y =10, 20
print(x, y)
y, x = x, y
print(x, y)
10 20
20 10
2、链状比较操作符
n = 10
print(1 < n < 20)
print(1 > n <= 9)
True
False
3、使用三元操作符来实现条件赋值
y = 20
x = 9 if (y == 10) else 8
print(x)
[表达式为真的返回值] if [表达式] else [表达式为假的返回值]
8

def small(a, b, c):
    return a if a<b and a<c else (b if b<a and b<c else c)
print(small(1, 0, 1))
print(small(1, 2, 2))
print(small(2, 2, 3))
print(small(5, 4, 3))
0
1
3
3

x = [m2 if m>10 else m4 for m in range(50)]
print(x)
[0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]
4、多行字符串
multistr = "select * from multi_row \
where row_id < 5"
print(multistr)
select * from multi_row where row_id < 5
multistr = """select * from multi_row
where row_id < 5"""
print(multistr)
select * from multi_row
where row_id < 5
multistr = ("select * from multi_row"
"where row_id < 5"
"order by age")
print(multistr)
select * from multi_rowwhere row_id < 5order by age

5、存储列表元素到新的变量
testList = [1, 2, 3]
x, y, z = testList    # 变量个数应该和列表长度严格一致
print(x, y, z)
1 2 3
6、打印引入模块的绝对路径
import threading
import Socket
print(threading)
print(socket)
<module 'threading' from 'd:\python351\lib\threading.py'>
<module 'socket' from 'd:\python351\lib\socket.py'>
7、交互环境下的“_”操作符
Python控制台,不论我们测试一个表达式还是调用一个方法,结果都会分配给一个临时变量“_”
8、字典/集合推导
testDic = {i: i * i for i in range(10)}
testSet = {i * 2 for i in range(10)}
print(testDic)
print(testSet)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
{0, 2, 4, 6, 8, 10, 12, 14, 16, 18}
9、调试脚本
用pdb模块设置断点
import pdb
pdb.ste_trace()

10、开启文件分享
python允许开启一个Http服务器从根目录共享文件
python -m http.server

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

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__fORMat__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
test = range(10)
print(dir(test))

['__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index', 'start', 'step', 'stop']
12、简化if语句

if m in [1, 2, 3, 4]:

if m==1 or m==2 or m==3 or m==4:
13、运行时检测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)
sorry, you are not running on python 2.7
current python version: 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]
14、组合多个字符串
test = ["I", "Like", "Python"]
print(test)
print("".join(test))
['I', 'Like', 'Python']
ILikePython
15、四种翻转字符串、列表的方式
5
3
1
16、用枚举在循环中找到索引
test = [10, 20, 30]
for i, value in enumerate(test):
    print(i, ':', value)
0 : 10
1 : 20
2 : 30
17、定义枚举量
class shapes:
    circle, square, triangle, quadrangle = range(4)
print(shapes.circle)
print(shapes.square)
print(shapes.triangle)
print(shapes.quadrangle)
0
1
2
3
18、从方法中返回多个值
def x():
    return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)
1 2 3 4
19、使用*运算符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)
z x y
1 2 3
10 20 30
20、用字典来存储表达式
stdcalc = {
    "sum": lambda x, y: x + y,
    "subtract": lambda x, y: x - y
}
print(stdcalc"sum")
print(stdcalc"subtract")
12
6
21、计算任何数的阶乘
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(3)
print(result)
6
22、找到列表中出现次数最多的数
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4, 4]
print(max(set(test), key=test.count))
4
23、重置递归限制
python限制递归次数到1000,可以用下面方法重置
import sys
x = 1200
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())

1000
1200
24、检查一个对象的内存使用
import sys
x = 1
print(sys.getsizeof(x))    # python3.5中一个32比特的整数占用28字节
28
25、使用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))

1016
888
26、用lambda 来模仿输出方法
import sys
lprint = lambda *args: sys.stdout.write(" ".join(map(str, args)))
lprint("python", "tips", 1000, 1001)

python tips 1000 1001
27、从两个相关序列构建一个字典
t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict(zip(t1, t2)))

{1: 10, 2: 20, 3: 30}
28、搜索字符串的多个前后缀
print("http://localhost:8888/notebooks/Untitled6.ipynb".startswith(("http://", "https://")))
print("http://localhost:8888/notebooks/Untitled6.ipynb".endswith((".ipynb", ".py")))
True
True
29、不使用循环构造一个列表
import itertools
import numpy as np
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test)))
[-1, -2, 30, 40, 25, 35]
30、实现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"))
None

--结束END--

本文标题: 30个Python常用小技巧

本文链接: https://www.lsjlt.com/news/192290.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 30个Python常用小技巧
    1、原地交换两个数字x, y =10, 20print(x, y)y, x = x, yprint(x, y)10 2020 102、链状比较操作符n = 10print(1 < n < 20)print(1 > n &...
    99+
    2023-01-31
    小技巧 常用 Python
  • python的30个编程技巧
     1、原地交换两个数字 1 x, y =10, 20 2 3 print(x, y) 4 5 y, x = x, y 6 7 print(x, y) 10 20 20 10 2、链状比较操作符 1 n = 10 2 3 pr...
    99+
    2023-01-30
    编程技巧 python
  • 分享11个常用JavaScript小技巧
    目录1.通过条件判断向对象添加属性2.检查对象中是否存在某个属性3.解构赋值4.循环遍历一个对象的key和value5.使用可选链(Optionalchaining)避免访问对象属性...
    99+
    2022-11-13
  • 分享Python中四个不常见的小技巧
    目录1. 引言2. 获取 n 个最大数字3. 获取 n 个最小数字4. 删除字符串的特定部分5. 从列表中删除重复元素6. 总结1. 引言 在编程界,每个人都希望自己可以写出世界上最...
    99+
    2022-11-11
  • 常用的29个CSS小技巧分享
    本篇内容主要讲解“常用的29个CSS小技巧分享”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“常用的29个CSS小技巧分享”吧!1.清除图片下方出现几像素的空白间...
    99+
    2022-10-19
  • 分享常用的3个C++小技巧
    目录1、头文件是引用<iostream.h>还是<iostream>?2、逗号分割表达式3、在main函数之前运行代码1、头文件是引用<iostream...
    99+
    2022-11-12
  • Linux命令技巧之30个必会的命令技巧
    在Unix/linux下,高效工作方式不是操作图形页面,而是命令行操作,命令行意味着更容易自动化。使用过Linux系统的朋友应该都知道它的命令行强大之处。本文讲述了Linux下的查找,删除,打包,解压,查询及VIM等30...
    99+
    2022-06-04
    Vim自动注释 tar命令 stat命令 linux批量解压 iptables网站跳转 查看linuxIP连接数 linux随机字符串
  • 20个Python常用技巧分享
    目录1.字符串反转2.每个单词的第一个字母大写3. 字符串查找唯一元素4.重复打印字符串和列表n次5.列表生成6.变量交换7.字符串拆分为子字符串列表8.多个字符串组合为一...
    99+
    2023-05-14
    Python常用技巧分享 Python常用技巧 Python技巧
  • 最实用的20个python小技巧
    目录1.用itertools排列2.单行条件表达式3. 反转字符串4. 使用 Assert 处理异常 5. 对多个输入使用拆分6. 用 zip() 转置矩阵7. 资源上下文管理器8....
    99+
    2022-11-12
  • 分享Python 的十个小技巧
      一. 列表、字典、集合、元组的使用  from random import randint, sample  # 列表解析  data = [randint(-10, 10) for _ in xrange(10)]  filter(l...
    99+
    2023-01-31
    小技巧 Python
  • windows8的50个使用小技巧 win8的50个小技巧大全
    1、锁屏启动之后,用户将首先看到Windows 8的锁屏界面,每当系统启动、恢复或登录的时候,锁屏就会出现。如果您使用的是触摸屏设备,那么用手指一扫然后输入密码就可以登录系统。如果不是触摸屏设备,那么就用鼠...
    99+
    2022-06-04
    小技巧 大全
  • python中常用的九个语法技巧
    目录前言数字分隔符交换变量值连续比较式字符串乘法列表拼接与乘法列表切片打包解包With语句对文件操作列表解析式总结前言 python语言简单、方便,尤其体现在语法方面,在其它语言中需...
    99+
    2022-11-13
  • 3个超有用的Python编程小技巧
    目录1、如何按照字典的值的大小进行排序 2、优雅的一次性判断多个条件 3、如何优雅的合并两个字典 1、如何按照字典的值的大小进行排序 我们知道,字典的本质是哈希表,本身是无法排序的...
    99+
    2022-11-12
  • 9个提高 Python 编程的小技巧
    目录01 交换变量02 字典推导和集合推导03 计数时使用Counter计数对象04 漂亮的打印出JSON05 解决FizzBuzz06 连接07 数值比较08 同时迭代两个列表09...
    99+
    2022-11-11
  • 五个节约生命的Python小技巧
    Python是一种强大且易上手的语言,语法简洁优雅,不像Java那么繁琐废话,并且有一些特殊的函数或语法可以让代码变得更加简短精悍。根据笔者经验,下面介绍常用的5个Python小技巧:字符串操作列表推导lambda 及 map() 函数if...
    99+
    2023-05-14
    Python 技巧
  • Python语言的10个小技巧分享
    这篇文章主要讲解了“Python语言的10个小技巧分享”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python语言的10个小技巧分享”吧!10个Python小技巧1. 用ZIP处理列表假设...
    99+
    2023-06-16
  • 【宝藏系列】20个常用的Python技巧
    【宝藏系列】20个常用的Python技巧 ...
    99+
    2023-08-31
    python windows 开发语言
  • Element-UI10个技巧小结
    目录el-scrollbar 滚动条el-upload 模拟点击el-select 下拉框选项过长el-input 首尾不能为空格el-input type=number 输入中文,...
    99+
    2022-11-12
  • 常用JavaScript小技巧有哪些
    这篇文章主要介绍“常用JavaScript小技巧有哪些”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“常用JavaScript小技巧有哪些”文章能帮助大家解决问题。1.通过条件判断向对象添加属性con...
    99+
    2023-06-30
  • Android ListView常用小技巧汇总
    ListView在我们Android项目中的地位是有目共睹的,相信几乎每一个App中都有它的身影。 ListView主要是用列表形式来加载数据,在特定情况下需要实现一些特殊功能:如刷新数据,加载数据,实现动画效果等。 作为我们常用的...
    99+
    2022-06-06
    技巧 listview Android
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作