news 2026/6/23 23:10:22

【Python零基础】30个Python实用技巧

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
【Python零基础】30个Python实用技巧

包含编程资料、学习路线图、源代码、软件安装包等!【[点击这里]】!

🔴1、原地交换两个数字
In[1]:x,y=10,20In[2]:print(x,y)1020In[3]:x,y=y,x In[4]:print(x,y)2010
🔴2、链状比较操作符
In[5]:n=10In[6]:result=1<n<20In[7]:result Out[7]:TrueIn[8]:result=1>n<=9In[9]:result Out[9]:False
🔴3、使用三元操作符来进行条件赋值
[表达式为真的返回值] if [表达式] else [表达式为假的返回值]
x=10if(y==9)else20
x=(classAify==1else classB)(param1,param2)
🔴4、多行字符串
In[20]:multistr="select*frommulti_row \...:where row_id<5" In[21]:multistr Out[21]:'select * from multi_row where row_id < 5'
In[23]:multistr="""select * from multi_row ...: where row_id < 5"""In[24]:multistr Out[24]:'select * from multi_row \nwhere row_id < 5'
In[25]:multistr=("select * from multi_row "...:"where row_id < 5"...:"orderby age")In[26]:multistr Out[26]:'select * from multi_row where row_id < 5 order by age'
🔴5、存储列表元素到新的变量中
In[27]:testlist=[1,2,3]In[28]:x,y,z=testlist In[29]:print(x,y,z)123
🔴6、打印引入模块的文件路径
In[30]:importthreading In[31]:importsocket In[32]:print(threading)<module'threading'from'/usr/local/lib/python3.5/threading.py'>In[33]:print(socket)<module'socket'from'/usr/local/lib/python3.5/socket.py'>
🔴7、交互环境下的"_"操作符
In[34]:2+3Out[34]:5In[35]:_ Out[35]:5In[36]:print(_)5
🔴8、字典/集合推导式
In[37]:testDict={i:i*iforiinrange(5)}In[38]:testSet={i*2for iinrange(5)}In[39]:testDict Out[39]:{0:0,1:1,2:4,3:9,4:16}In[40]:testSet Out[40]:{0,2,4,6,8}
🔴9、调试脚本
importpdb pdb.set_trace()
🔴10、开启文件分享
python3-mhttp.server
🔴11、检查Python中的对象
In[41]:test=[1,3,5,7]In[42]: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']
🔴12、简化if语句
ifmin[1,3,5,7]:
ifm==1or m==3or m==5or m==7:
🔴13、运行时检测Python版本
importsys#Detect the Python version currently in use.ifnothasattr(sys,"hexversion")orsys.hexversion!=50660080:print("Sorry, you aren't running on Python 3.5n")print("Please upgrade to 3.5.n")sys.exit(1)#Print Python version in a readable format.print("Current Python version: ",sys.version)
Python3.5.1(default,Dec2015,13:05:11)[GCC4.8.2]onlinux CurrentPythonversion:3.5.2(default,Aug222016,21:11:05)[GCC5.3.0]
🔴14、组合多个字符串
In[44]:test=['I','Like','Python','automation']In[45]:''.join(test)Out[45]:'ILikePythonautomation'
🔴15、四种翻转字符串/列表的方式
In[49]:testList=[1,3,5]In[50]:testList.reverse()In[51]:testList Out[51]:[5,3,1]
In[52]:forelementinreversed([1,3,5]):...:print(element)...:531
In[53]:"Test Python"[::-1]Out[53]:'nohtyP tseT'
[1,3,5][::-1]
🔴16、在python中使用枚举量
In[56]:classShapes:...:Circle,Square,Triangle,Quadrangle=range(4)...:In[57]:Shapes.Circle Out[57]:0In[58]:Shapes.Square Out[58]:1In[59]:Shapes.Triangle Out[59]:2In[60]:Shapes.Quadrangle Out[60]:3
🔴17、从方法中返回多个值
In[61]:defx():...:return1,2,3,4...:In[62]:a,b,c,d=x()In[63]:print(a,b,c,d)1234
🔴18、从两个相关的序列构建一个字典
In[92]:t1=(1,2,3)In[93]:t2=(10,20,30)In[94]:dict(zip(t1,t2))Out[94]:{1:10,2:20,3:30}
🔴19、将字典拆分为键和值的列表
c={'Bob':'male','Jack':'male','Mary':'female','Tom':'male'}keys1=list(c.keys())#['Bob', 'Jack', 'Tom', 'Mary']values1=list(c.values())#['male', 'male', 'male', 'female']
🔴20、一行代码计算任何数的阶乘
In[75]:importfunctools In[76]:result=(lambdak:functools.reduce(int.__mul__,range(1,k+1),1))(3)In[77]:result Out[77]:6
🔴21、重置递归限制
importsys x=1001print(sys.getrecursionlimit())sys.setrecursionlimit(x)print(sys.getrecursionlimit())#1-> 1000#2-> 100
🔴22、检查一个对象的内存使用
importsys x=1print(sys.getsizeof(x))#-> 24
In[86]:importsys In[87]:x=1In[88]:sys.getsizeof(x)Out[88]:28
🔴23、使用slots来减少内存开支
importsys classFileSystem(object):def__init__(self,files,folders,devices):self.files=files self.folders=folders self.devices=devicesprint(sys.getsizeof(FileSystem))classFileSystem1(object):__slots__=['files','folders','devices']def__init__(self,files,folders,devices):self.files=files self.folders=folders self.devices=devicesprint(sys.getsizeof(FileSystem1))#In Python 3.5#1-> 1016#2-> 888
🔴24、使用lambda来模仿输出方法
In[89]:importsys In[90]:lprint=lambda*args:sys.stdout.write("".join(map(str,args)))In[91]:lprint("python","tips",1000,1001)Out[91]:pythontips1000100118
🔴25、使用字典来存储选择操作
In[70]:stdacl={...:'sum':lambdax,y:x+y,...:'subtract':lambdax,y:x-y...:}In[73]:stdacl['sum'](9,3)Out[73]:12In[74]:stdacl['subtract'](9,3)Out[74]:6
🔴26、一行代码搜索字符串的多个前后缀
In[95]:print("http://www.google.com".startswith(("http://","https://")))TrueIn[96]:print("http://www.google.co.uk".endswith((".com",".co.uk")))True
🔴27、不使用循环构造一个列表
In[101]:test=[[-1,-2],[30,40],[25,35]]In[102]:importitertools In[103]:print(list(itertools.chain.from_iterable(test)))[-1,-2,30,40,25,35]
🔴28、在Python中实现一个真正的switch-case语句
In[104]:defxswitch(x):...:returnxswitch._system_dict.get(x,None)...:In[105]:xswitch._system_dict={'files':10,'folders':5,'devices':2}In[106]:print(xswitch('default'))NoneIn[107]:print(xswitch('devices'))2
🔴29、计数时使用Counter计数对象
>>>fromcollectionsimportCounter>>>c=Counter(hello world)>>>c Counter({l:3,o:2,:1,e:1,d:1,h:1,r:1,w:1})>>>c.most_common(2)[(l,3),(o,2)]
🔴30、漂亮的打印出JSON
>>>importjson>>>print(json.dumps(data))# No indention{"status":"OK","count":2,"results":[{"age":27,"name":"Oz","lactose_intolerant":true},{"age":29,"name":"Joe","lactose_intolerant":false}]}>>>print(json.dumps(data,indent=2))# With indention{"status":"OK","count":2,"results":[{"age":27,"name":"Oz","lactose_intolerant":true},{"age":29,"name":"Joe","lactose_intolerant":false}]}

🟢总结

🟡文末福利

🔴包含编程资料、学习路线图、源代码、软件安装包等!【点击这里】领取!

可以扫描下方二维码领取【保证100%免费


加粗样式

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/23 11:03:19

智元AGIBOT荣登具身智能机器人技术研发排行榜TOP1

当前&#xff0c;全球具身智能机器人产业正进入技术创新发展的关键期。随着数据采集、模型训练、仿真验证等基础技术体系的不断完善&#xff0c;具身智能机器人的技术壁垒正在被逐步突破。本文将从多个维度&#xff0c;为您解析当前在技术研发方面最具实力的5家具身智能机器人公…

作者头像 李华
网站建设 2026/6/23 17:49:13

Gitee vs GitHub 2025深度评测:国产代码托管平台的崛起与超越

Gitee vs GitHub 2025深度评测&#xff1a;国产代码托管平台的崛起与超越 在数字化转型加速的当下&#xff0c;代码托管平台已成为开发者生态的核心基础设施。作为国内领先的代码托管平台&#xff0c;Gitee经过多年发展已形成完整的技术生态链。最新数据显示&#xff0c;Gitee注…

作者头像 李华
网站建设 2026/6/23 22:22:18

JVM 安全与沙箱深度解析

文章目录JVM 安全与沙箱深度解析字节码校验、ClassLoader隔离、攻击防护全面指南&#x1f4cb; 目录&#x1f6e1;️ 一、JVM安全模型架构解析&#x1f4a1; JVM安全架构层次&#x1f3af; JVM安全管理器实现&#x1f50d; 二、字节码校验机制深度剖析&#x1f4a1; 字节码验证…

作者头像 李华
网站建设 2026/6/23 17:52:29

t-SNE快速降维算法详解与实现

t-SNE&#xff08;t-distributed Stochastic Neighbor Embedding&#xff09;是一种非常有效的非线性降维技术&#xff0c;特别适用于高维数据的可视化。 t-SNE算法核心原理 算法概述 t-SNE通过保留数据点之间的相似性将高维数据映射到低维空间&#xff08;通常是2D或3D&#x…

作者头像 李华
网站建设 2026/6/23 17:48:30

Python编程入门从零开始掌握基础语法一

&#x1f49d;&#x1f49d;&#x1f49d;欢迎莅临我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 持续学习&#xff0c;不断…

作者头像 李华