给大家安利一个免费且实用的 Python 刷题(面经大全)网站,👉点击跳转到网站。
如果您让任何 Python 程序员讲述 Python 的优势,他会引用简洁和高可读性作为最有影响力的优势。在本 Python 教程中,我们将介绍许多基本的 Python 教程和技巧,这些技巧和技巧将验证上述两点。
自从我开始使用 Python 以来,我一直在收集这些有用的快捷方式。还有什么事比分享我们所知道的并且可以使他人受益的东西更加有意义?
所以今天,我带来了一些基本的 Python 教程和技巧。所有这些技巧都可以帮助您减少代码并优化执行。此外,您可以在处理常规任务时轻松地在实时项目中使用它们。
目录
1.就地交换两个数字2.比较运算符的链接3.使用三元运算符进行条件赋值。4.使用多行字符串。5.将列表元素存储到新变量中。6.打印导入模块的文件路径。7.使用交互式“_”运算符。8.字典/集合理解。9.调试脚本。10.设置文件共享。11.在 Python 中检查对象。12.简化 if 语句。13.在运行时检测 Python 版本。14.组合多个字符串。15.反转 string/list 的四种方法。16.玩枚举。17.在 Python 中使用枚举。18.从函数返回多个值。19.使用 splat 运算符解包函数参数。20.使用字典来存储 switch。21.计算一行中任意数字的阶乘。22.查找列表中出现频率最高的值。23.重置递归限制。24.检查对象的内存使用情况。25.使用 slots 减少内存开销。26.Lambda 模仿打印功能。27.从两个相关序列创建字典。28.在线搜索字符串中的多个前缀。29.形成一个统一的列表,不使用任何循环。30.在 Python 中实现真正的 switch-case 语句。总结——Python 提示和技巧
技巧1 就地交换两个数字
Python 提供了一种在一行中进行赋值和交换的直观方式。请参考下面的例子。
1 | python复制代码x, y = 10, 20 |
右边的赋值为一个新的元组播种。而左边的立即将那个(未引用的)元组解包到名称 <a>
和 <b>
。
分配完成后,新元组将被取消引用并标记为垃圾收集。变量的交换也发生在最终。回到目录
技巧2 比较运算符的链接。
比较运算符的聚合是另一个有时可以派上用场的技巧。
1 | python复制代码n = 10 |
python复制代码[on_true] if [expression] else [on_false]
1 |
|
python复制代码x = 10 if (y == 9) else 20
1 |
|
python复制代码x = (classA if y == 1 else classB)(param1, param2)
1 |
|
python复制代码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))
#Output
#0 #1 #2 #3
1 |
|
python复制代码[m2 if m > 10 else m4 for m in range(50)]
#=> [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]
1 |
|
python复制代码multiStr = “select * from multi_row
where row_id < 5”
print(multiStr)
select * from multi_row where row_id < 5
1 |
|
python复制代码multiStr = “””select * from multi_row
where row_id < 5”””
print(multiStr)
#select * from multi_row
#where row_id < 5
1 |
|
python复制代码multiStr= (“select * from multi_row “
“where row_id < 5 “
“order by age”)
print(multiStr)
#select * from multi_row where row_id < 5 order by age
1 |
|
python复制代码testList = [1,2,3]
x, y, z = testList
print(x, y, z)
#-> 1 2 3
1 |
|
python复制代码import threading
import socket
print(threading)
print(socket)
#1- <module ‘threading’ from ‘/usr/lib/python2.7/threading.py’>
#2- <module ‘socket’ from ‘/usr/lib/python2.7/socket.py’>
1 |
|
python复制代码>>> 2 + 1
3
_
3
print _
3
1 |
|
python复制代码testDict = {i: i * i for i in xrange(10)}
testSet = {i * 2 for i in xrange(10)}
print(testSet)
print(testDict)
#set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
#{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
1 |
|
python复制代码import pdb
pdb.set_trace()
1 |
|
python复制代码python -m SimpleHTTPServer
1 |
|
python复制代码python3 -m http.server
1 |
|
python复制代码test = [1, 3, 5, 7]
print( dir(test) )
1 |
python复制代码[‘add‘, ‘class‘, ‘contains‘, ‘delattr‘, ‘delitem‘, ‘delslice‘, ‘doc‘, ‘eq‘, ‘format‘, ‘ge‘, ‘getattribute‘, ‘getitem‘, ‘getslice‘, ‘gt‘, ‘hash‘, ‘iadd‘, ‘imul‘, ‘init‘, ‘iter‘, ‘le‘, ‘len‘, ‘lt‘, ‘mul‘, ‘ne‘, ‘new‘, ‘reduce‘, ‘reduce_ex‘, ‘repr‘, ‘reversed‘, ‘rmul‘, ‘setattr‘, ‘setitem‘, ‘setslice‘, ‘sizeof‘, ‘str‘, ‘subclasshook‘, ‘append’, ‘count’, ‘extend’, ‘index’, ‘insert’, ‘pop’, ‘remove’, ‘reverse’, ‘sort’]
1 |
|
python复制代码if m in [1,3,5,7]:
1 |
|
python复制代码if m==1 or m==3 or m==5 or m==7:
1 |
|
python复制代码import sys
#Detect the Python version currently in use.
if not hasattr(sys, “hexversion”) or sys.hexversion != 50660080:
print(“Sorry, you aren’t running on Python 3.5\n”)
print(“Please upgrade to 3.5.\n”)
sys.exit(1)
#Print Python version in a readable format.
print(“Current Python version: “, sys.version)
1 |
|
python复制代码Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
Sorry, you aren’t running on Python 3.5
Please upgrade to 3.5.
1 |
|
python复制代码Python 3.5.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
Current Python version: 3.5.2 (default, Aug 22 2016, 21:11:05)
[GCC 5.3.0]
1 |
|
python复制代码>>> test = [‘I’, ‘Like’, ‘Python’, ‘automation’]
1 |
|
python复制代码>>> print ‘’.join(test)
1 |
|
python复制代码testList = [1, 3, 5]
testList.reverse()
print(testList)
#-> [5, 3, 1]
1 |
|
python复制代码for element in reversed([1,3,5]): print(element)
#1-> 5
#2-> 3
#3-> 1
1 |
|
python复制代码”Test Python”[::-1]
1 |
|
python复制代码[1, 3, 5][::-1]
1 |
|
python复制代码testlist = [10, 20, 30]
for i, value in enumerate(testlist):
print(i, ‘: ‘, value)
#1-> 0 : 10
#2-> 1 : 20
#3-> 2 : 30
1 |
|
python复制代码class Shapes:
Circle, Square, Triangle, Quadrangle = range(4)
print(Shapes.Circle)
print(Shapes.Square)
print(Shapes.Triangle)
print(Shapes.Quadrangle)
#1-> 0
#2-> 1
#3-> 2
#4-> 3
1 |
|
python复制代码# function returning multiple values.
def x():
return 1, 2, 3, 4
Calling the above function.
a, b, c, d = x()
print(a, b, c, d)
1 |
|
python复制代码def test(x, y, z):
print(x, y, z)
testDict = {‘x’: 1, ‘y’: 2, ‘z’: 3}
testList = [10, 20, 30]
test(testDict)
test(*testDict)
test(*testList)
#1-> x y z
#2-> 1 2 3
#3-> 10 20 30
1 |
|
python复制代码stdcalc = {
‘sum’: lambda x, y: x + y,
‘subtract’: lambda x, y: x - y
}
print(stdcalc‘sum’)
print(stdcalc‘subtract’)
#1-> 12
#2-> 6
1 |
|
python复制代码result = (lambda k: reduce(int.mul, range(1,k+1),1))(3)
print(result)
#-> 6
1 |
|
python复制代码import functools
result = (lambda k: functools.reduce(int.mul, range(1,k+1),1))(3)
print(result)
1 |
|
python复制代码test = [1,2,3,4,2,2,3,1,4,4,4]
print(max(set(test), key=test.count))
#-> 4
1 |
|
python复制代码import sys
x=1001
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
#1-> 1000
#2-> 1001
1 |
|
python复制代码import sys
x=1
print(sys.getsizeof(x))
#-> 24
1 |
|
python复制代码import sys
x=1
print(sys.getsizeof(x))
#-> 28
1 |
|
python复制代码import sys
class FileSystem(object):
def __init__(self, files, folders, devices):
self.files = files
self.folders = folders
self.devices = devices
print(sys.getsizeof( FileSystem ))
class FileSystem1(object):
__slots__ = ['files', 'folders', 'devices']
def __init__(self, files, folders, devices):
self.files = files
self.folders = folders
self.devices = devices
print(sys.getsizeof( FileSystem1 ))
#In Python 3.5
#1-> 1016
#2-> 888
1 |
|
python复制代码import sys
lprint=lambda *args:sys.stdout.write(“ “.join(map(str,args)))
lprint(“python”, “tips”,1000,1001)
#-> python tips 1000 1001
1 |
|
python复制代码t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict (zip(t1,t2)))
#-> {1: 10, 2: 20, 3: 30}
1 |
|
python复制代码print(“http://www.baidu.com".startswith((“http://“, “https://“)))
print(“https://juejin.cn".endswith((“.com”, “.cn”)))
#1-> True
#2-> True
1 |
|
python复制代码import itertools
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test)))
#-> [-1, -2, 30, 40, 25, 35]
1 |
|
python复制代码def unifylist(l_input, l_target):
for it in l_input:
if isinstance(it, list):
unifylist(it, l_target)
elif isinstance(it, tuple):
unifylist(list(it), l_target)
else:
l_target.append(it)
return l_target
test = [[-1, -2], [1,2,3, [4,(5,[6,7])]], (30, 40), [25, 35]]
print(unifylist(test,[]))
#Output => [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]
1 |
|
python复制代码import more_itertools
test = [[-1, -2], [1, 2, 3, [4, (5, [6, 7])]], (30, 40), [25, 35]]
print(list(more_itertools.collapse(test)))
#Output=> [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]
1 |
|
python复制代码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’))
#1-> None
#2-> 2
---
总结——Python 提示和技巧
----------------
我们希望上面给出的基本 Python 提示和技巧将帮助您快速有效地完成任务。您可以将它们用于您的作业和项目。
我已经写了很长一段时间的技术博客,这是我的一篇技巧教程。希望你们会喜欢!这里汇总了我的全部原创及作品源码:[Github](https://github.com/wanghao221/)、[Gitee](https://gitee.com/haiyongcsdn/haiyong)
如果你真的从这篇文章中学到了一些新东西,喜欢它,收藏它并与你的小伙伴分享。🤗最后,不要忘了❤或📑支持一下哦
**本文转载自:** [掘金](https://juejin.cn/post/6981262439069253640)
*[开发者博客 – 和开发相关的 这里全都有](https://dev.newban.cn/)*