zoukankan      html  css  js  c++  java
  • python 编程的30个技巧

    Python 编程的30个技巧

    引言

    本文学习的是 30 tricks for python programmers , 理解后整理为本学习笔记。

    1. 就地替换两个数字

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

    2. 比较运算符的连接

    n = 10
    result = 1 < n < 20
    print(result)
    True
    
    result = 1 > n <= 9
    print(result)
    False
    

    3. 使用三元运算符进行赋值

    [on_true] if [expression] else [on_false]

    x = 10 if (y == 9) else 20
    
    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, 2, 2))
    
    [m**2 if m > 10 else m**4 for m in range(50)]
    

    4. 使用多行字符串

    • The basic approach is to use backslashes which derive itself from C language.
    • One more trick is to use the triple-quotes.
    • the final solution is to split the string into multi lines and enclose the entire string in parenthesis.
    multiStr = "select * from multi_row 
    where row_id < 5"
    print(multiStr)
    # output
    # select * from multi_row where row_id < 5
    
    multiStr = "select * from multi_row 
    where row_id < 5"
    print(multiStr)
    # output
    # 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)
    <module 'threading' from 'D:\Anaconda\lib\threading.py'>
    <module 'socket' from 'D:\Anaconda\lib\socket.py'>
    

    7. 使用交互式“ _”运算符

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

    “ _”引用最后执行的表达式的输出。

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

    8. 字典-集合推导式

    就像我们使用列表推导式一样,我们也可以使用字典/集合推导式。

    print(testDict)
    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}
    
    type(testDict)
    Out[18]: dict
    
    type(testSet)
    Out[19]: set
    

    9. 调试脚本

    在''''模块的帮助下,我们可以在Python脚本中设置断点。

    我们可以在脚本的任何地方指定<pdb.set_trace()>,并在那里设置断点。它非常方便。

    import pdb
    pdb.set_trace()
    

    10. 安装文件共享

    Python允许运行HTTP服务器,您可以使用它来共享来自服务器根目录的文件。下面是启动服务器的命令。

    python3 -m http.server
    

    11. 在Python中检查一个对象

    我们可以通过调用dir()方法来检查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__', '__init_subclass__', '__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语句

    # 要验证多个值,可以采用以下方法。
    if m in [1,3,5,7]:
    # 而不是:
    if m==1 or m==3 or m==5 or m==7:
    

    13. 在运行时检测Python版本

    
    

    14. 结合多个字符串

    >>> test = ['I', 'Like', 'Python', 'automation']
    >>> print ''.join(test)
    

    15. 反转字符串/列表的四种方法

    # Reverse the list itself.
    testList = [1, 3, 5]
    testList.reverse()
    print(testList)
    
    #-> [5, 3, 1]
    
    # Reverse while iterating in a loop.
    for element in reversed([1,3,5]): print(element)
    
    #1-> 5
    #2-> 3
    #3-> 1
    
    # Reverse a string in line.
    "Test Python"[::-1]
    
    # Reverse a list using slicing.
    [1, 3, 5][::-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中枚举的使用

    我们可以使用以下方法来创建enum定义。

    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中的函数确实会返回多个值。

    # 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 2 3 4
    

    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
    

    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.计算一行中任意数字的阶乘

    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.检查对象的内存使用情况

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

    25.使用_slots__来减少内存开销

    您是否注意到您的Python应用程序消耗了大量资源,尤其是内存?这里有一个技巧,它使用<_ slots__>类变量来在一定程度上减少内存开销。

    显然,您可以从结果中看到内存使用方面的节省。但是,当类的内存开销不必要地大时,您应该使用_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. 模仿打印函数

    use 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://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]
    

    30.在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
    
  • 相关阅读:
    Intent 传递Map数据
    android 读取.properties文件
    android 复制到剪切板
    SVN Update Error: Please execute the 'Cleanup' command
    Win8安装程序出现2502、2503错误解决方法
    启动系统自带的应用程序
    解决底部Button遮挡ListView最后一项内容的bug
    Intent传递list集合时异常解决
    Tomcate 启动异常,java.net.BindException: Address already in use: JVM_Bind:80的解决办法
    【Web】阿里icon图标gulp插件(gulp-qc-iconfont)
  • 原文地址:https://www.cnblogs.com/songbiao/p/12464663.html
Copyright © 2011-2022 走看看