给大家安利一个免费且实用的 Python 刷题(面经大全)网站,👉点击跳转到网站。
直接跳到末尾 去评论区领书
今天,我给大家带来了一些基本的 Python 编程技巧。所有这些技巧都可以帮助您减少代码并优化执行。你可以在处理常规任务时轻松地在实时项目中使用它们。
技巧1 就地交换两个数字
Python 提供了一种在一行中进行赋值和交换的直观方式。请参考下面的例子。
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
#1 (10, 20)
#2 (20, 10)
右边的赋值为一个新的元组播种。而左边的立即将那个(未引用的)元组解包到名称 <a>
和 <b>
。
分配完成后,新元组将被取消引用并标记为垃圾收集。变量的交换也发生在最终。
技巧3 使用三元运算符进行条件赋值。
三元运算符是 if-else 语句的快捷方式,也称为条件运算符。
[on_true] if [expression] else [on_false]
以下是一些示例,您可以使用它们使代码紧凑简洁。
下面的语句与它的意思相同,即“如果 y 为 9,则将 10 分配给 x,否则将 20 分配给 x ”。如果需要,我们可以扩展运算符的链接。
x = 10 if (y == 9) else 20
同样,我们可以对类对象做同样的事情。
x = (classA if y == 1 else classB)(param1, param2)
在上面的例子中,classA 和 classB 是两个类,其中一个类构造函数将被调用。
下面是一个没有的例子。加入评估最小数字的条件。
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 #2 #3
我们甚至可以在列表推导式中使用三元运算符。
[m**2 if m > 10 else m**4 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]
技巧5 将列表元素存储到新变量中
我们可以使用一个列表来初始化一个 no。的变量。在解压列表时,变量的数量不应超过编号。列表中的元素。
testList = [1,2,3]
x, y, z = testList
print(x, y, z)
#-> 1 2 3
技巧7 使用交互式“_”运算符
这是一个有用的功能,我们很多人都不知道。
在 Python 控制台中,每当我们测试表达式或调用函数时,结果都会发送到临时名称 _(下划线)。
>>> 2 + 1
3
>>> _
3
>>> print _
3
“_”引用上次执行的表达式的输出。
技巧9 调试脚本
我们可以在
import pdb
pdb.set_trace()
我们可以在脚本的任何地方指定
技巧11 在 Python 中检查对象
我们可以通过调用 dir() 方法来检查 Python 中的对象。这是一个简单的例子。
test = [1, 3, 5, 7]
print( dir(test) )
['__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']
技巧13 在运行时检测 Python 版本
有时,如果当前运行的 Python 引擎低于支持的版本,我们可能不想执行我们的程序。为此,您可以使用以下代码片段。它还以可读格式打印当前使用的 Python 版本。
import sys
# 检测当前使用的 Python 版本。
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)
# 以可读格式打印 Python 版本。
print("Current Python version: ", sys.version)
或者,您可以在上面的代码中使用sys.version_info >= (3, 5)替换sys.hexversion!= 50660080。这是一位知情读者的建议。
在 Python 2.7 上运行时的输出。
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.
在 Python 3.5 上运行时的输出。
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]
技巧15 反转 string/list 的四种方法
反转列表本身
testList = [1, 3, 5]
testList.reverse()
print(testList)
#-> [5, 3, 1]
在循环中迭代时反转
for element in reversed([1,3,5]): print(element)
#1-> 5
#2-> 3
#3-> 1
反转一个字符串
"Test Python"[::-1]
这使输出为“nohtyP tseT”
使用切片反转列表
[1, 3, 5][::-1]
上面的命令将输出 [5, 3, 1]。
技巧17 在 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
技巧19 使用 splat 运算符解包函数参数。
splat 运算符提供了一种解压参数列表的艺术方式。为清楚起见,请参阅以下示例。
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
技巧21 计算一行中任意数字的阶乘。
Python 2.x.
result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3)
print(result)
#-> 6
Python 3.x.
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1))(3)
print(result)
#-> 6
技巧23 重置递归限制。
Python 将递归限制限制为 1000。我们可以重置它的值。
import sys
x=1001
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
#1-> 1000
#2-> 1001
请仅在需要时应用上述技巧。
技巧25 使用 __slots__ 减少内存开销。
你有没有观察到你的 Python 应用程序消耗了大量资源,尤其是内存?这是使用<__slots__>
类变量在一定程度上减少内存开销的一种技巧。
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
显然,您可以从结果中看到内存使用量有所节省。但是当一个类的内存开销不必要地大时,你应该使用 __slots__
。仅在分析应用程序后执行此操作。否则,您将使代码难以更改并且没有真正的好处。
技巧27 从两个相关序列创建字典。
t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict (zip(t1,t2)))
#-> {1: 10, 2: 20, 3: 30}
技巧29 形成一个统一的列表,不使用任何循环。
import itertools
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test)))
#-> [-1, -2, 30, 40, 25, 35]
如果您有一个包含嵌套列表或元组作为元素的输入列表,请使用以下技巧。但是,这里的限制是它使用了 for 循环。
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,[]))
#输出=> [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]
统一包含列表和元组的列表的另一种更简单的方法是使用 Python 的 < more_itertools > 包。它不需要循环。只需执行 < pip install more_itertools >,如果还没有的话。
import more_itertools
test = [[-1, -2], [1, 2, 3, [4, (5, [6, 7])]], (30, 40), [25, 35]]
print(list(more_itertools.collapse(test)))
#输出=> [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]
🥇 评论区抽粉丝送书啦
书籍:赠送 3 本《深入浅出Python数据分析》,更多介绍和目录可以点击下面链接了解。
{% link 抽奖入口, https://mp.weixin.qq.com/s/6PHBegCSZ12i8Yab4iWj6g, https://blog.haiyong.site/img/demo/220905-01.jpg %}