推荐30个好用的Python编程技巧

admin 2022年2月7日14:38:21评论38 views字数 7123阅读23分44秒阅读模式

1. 直接交换2个数字的位置

Python 提供了一种直观的方式在一行代码中赋值和交换(变量值)。如下所示:

x, y = 10, 20
print(x, y)

x, y = y, x
print(x, y)

#1 (10, 20)
#2 (20, 10)


在上面代码中,赋值的右侧形成了一个新元组,而左侧则立刻将该(未被引用的)元组解包到名称<a>和<b>。

待赋值完成后,新元组就变成了未被引用状态,并且被标为可被垃圾回收,最终也就发生了数字交换。

2.链接比较操作符

比较运算符的聚合是另一种有时用起来很顺手的技巧。


n = 10
result = 1 < n < 20
print(result)

# True

result = 1 > n <= 9
print(result)

# False


3. 使用三元操作符进行条件赋值

三元操作符是 if-else 语句(也就是条件操作符)的快捷操作:

[on_true] if [expression] else [on_false]


下面举两个例子例子,展示一下可以用这种技巧让你的代码更紧凑更简洁。

下面的语句意思是“如果 y 为 9,就向 x 赋值 10,否则向 x 赋值 20”。如果需要,我们可以扩展这个操作符链接:

x = 10 if (y == 9) else 20


同样,我们对类对象也可以这样操作:

x = (classA if y == 1 else classB)(param1, param2)


在上面这个例子中,classA 与 classB 是两个类,其中一个类构造函数会被调用。

4. 使用多行字符串

这个方法就是使用源自 C 语言的反斜杠:

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_row where row_id < 5 order 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)

#1- <module 'threading' from '/usr/lib/python2.7/threading.py'>
#2- <module 'socket' from '/usr/lib/python2.7/socket.py'>

7. 使用交互式“_”操作符

其实这是个相当有用的功能,只是我们很多人并没有注意到。

在 Python 控制台中,每当我们测试一个表达式或调用一个函数时,结果都会分配一个临时名称,_(一条下划线)。

>>> 2 + 1
3
>>> _
3
>>> print _
3


这里的“_”是上一个执行的表达式的结果。

8. 字典/集合推导

就像我们使用列表表达式一样,我们也可以使用字典/集合推导。非常简单易用,也很有效,示例如下:


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}


注意:在这两个语句中,<:>只有一处差异。另外,如果想用 Python3 运行以上代码,要把 <xrange> 替换为 <range>。

9. 调试脚本

我们可以借助 <pdb> 模块在 Python 脚本中设置断点,如下所示:


import pdb
pdb.set_trace()


我们可以在脚本的任意位置指定<pdb.set_trace()> ,然后在那里设置一个断点,非常方便。

10. 设置文件分享

Python 能让我们运行 HTTP 服务器,可以用于分享服务器根目录中的文件。启动服务器的命令如下:


# Python 2:
python -m SimpleHTTPServer

# Python 3:
python3 -m http.server


上述命令会在默认端口 8000 启动一个服务器,你也可以使用自定义端口,将端口作为最后元素传入上述命令中即可。

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']

12. 使用in操作符简化if语句

我们可以通过如下方式来验证多个值:

if m in [1,3,5,7]:


而不用这样:

if m==1 or m==3 or m==5 or m==7:


对于in操作符,我们也可以用‘{1,3,5,7}’而不是‘[1,3,5,7]’,因为‘set’可以通过O(1)获取每个元素。


13. 在运行时检测Python的版本

有时如果当前运行的 Python 低于支持版本时,我们可能不想执行程序。那么就可以用下面的代码脚本检测 Python 的版本。还能以可读格式打印出当前所用的 Python 版本。


import sys

#检测当前所用的Python版本
if not hasattr(sys, "hexversion") or sys.hexversion != 50660080:
print("Sorry, you aren't running on Python 3.5n")
print("Please upgrade to 3.5.n")
sys.exit(1)

#以可读格式打印出Python版本
print("Current Python version: ", sys.version)


另外,你可以将上面代码中的 sys.hexversion!= 50660080 替换为 sys.version_info >= (3, 5)。

在 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]

14. 组合多个字符串

如果你想拼接列表中的所有 token,那么看看下面的例子就明白了:

>>> test = ['I', 'Like', 'Python', 'automation']


现在我们从上面列表的元素中创建一个字符串:

>>> print ''.join(test)

15. 翻转字符串/列表的4种方式


#翻转列表本身
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]。

16. 使用枚举

使用枚举可以很容易地在循环中找到索引:

testlist = [10, 20, 30]
for i, value in enumerate(testlist):
print(i, ': ', value)

#1-> 0 : 10
#2-> 1 : 20
#3-> 2 : 30


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

18. 从函数中返回多个值

支持这种功能的编程语言并不多,然而,Python 中的函数可以返回多个值。

可以参考下面的例子看看是怎么做到的:


# 返回多个值的函数
def x():
return 1, 2, 3, 4

# 调用上面的函数
a, b, c, d = x()

print(a, b, c, d)

#-> 1 2 3 4

19. 使用*运算符解压缩函数参数

*运算符提供了一种很艺术的方式来解压缩参数列表,参看如下示例:

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


20. 使用字典来存储表达式

stdcalc = {
'sum': lambda x, y: x + y,
'subtract': lambda x, y: x - y
}

print(stdcalc['sum'](9,3))
print(stdcalc['subtract'](9,3))

#1-> 12
#2-> 6


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


22.找到一个列表中的出现最频繁的值


test = [1,2,3,4,2,2,3,1,4,4,4]
print(max(set(test), key=test.count))

#-> 4


23. 重置递归限制

Python 将递归限制到 1000,我们可以重置这个值:

import sys

x=1001
print(sys.getrecursionlimit())

sys.setrecursionlimit(x)
print(sys.getrecursionlimit())

#1-> 1000
#2-> 1001


提示:在有必要时才使用该技巧。

24. 检查一个对象的内存使用

在 Python 2.7 中,一个 32-bit 的整数值会占用 24 字节,而在 Python 3.5 中会占用 28 字节。我们可以调用<getsizeof> 方法来验证内存使用。


在 Python 2.7 中:

import sys
x=1
print(sys.getsizeof(x))

#-> 24


在 Python 3.5 中:

import sys
x=1
print(sys.getsizeof(x))

#-> 28

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


很明显,从解雇中可以看到节省了一些内存。但是应当在一个类的内存占用大得没有必要时再使用这种方法。对应用进行性能分析后再使用它,不然除了会让代码难以改动外没有什么好处。

26. 使用lamda来模仿输出方法

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://www.google.com".startswith(("http://", "https://")))
print("http://www.google.co.uk".endswith((".com", ".co.uk")))

#1-> True
#2-> True

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,[]))

#Output => [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]

30. 在Python中实现一个真正的switch-case语句

下面是使用字典模仿一个 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'))

#1-> None
#2-> 2


结语

希望上面列出的这些 Python 技巧和建议能帮你快速和高效地完成 Python 开发,可以在项目中应用它们。

【历史文章】:

【入门教程】常见的Web漏洞--XSS

【入门教程】常见的Web漏洞--SQL注入

sql注入--入门到进阶

短信验证码安全常见逻辑漏洞

最全常见Web安全漏洞总结及推荐解决方案

常见的Web应用的漏洞总结(原理、危害、防御)

代码审计常见漏洞总结

Web安全漏洞的靶场演示

13 款 Linux 比较实用的工具

xss攻击、绕过最全总结


学习更多技术,关注我:

觉得文章不错给点个‘再看’吧推荐30个好用的Python编程技巧

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2022年2月7日14:38:21
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   推荐30个好用的Python编程技巧https://cn-sec.com/archives/767141.html

发表评论

匿名网友 填写信息