zoukankan      html  css  js  c++  java
  • python实用30个小技巧

    python实用30个小技巧

    展开
    1.原地交换两个数字
    Python 提供了一个直观的在一行代码中赋值与交换(变量值)的方法,请参见下面的示例:

    In [1]: x,y = 10 ,20 
    
    In [2]: print(x,y)
    10 20
    
    In [3]: x, y = y, x 
    
    In [4]: print(x,y)
    20 10

    赋值的右侧形成了一个新的元组,左侧立即解析(unpack)那个(未被引用的)元组到变量 <x> 和 <y>。

    一旦赋值完成,新的元组变成了未被引用状态并且被标记为可被垃圾回收,最终也完成了变量的交换。

    2.链状比较操作符
    比较操作符的聚合是另一个有时很方便的技巧:

    In [5]: n = 10 
    
    In [6]: result = 1 < n < 20 
    
    In [7]: result 
    Out[7]: True
    
    In [8]: result = 1 > n <= 9 
    
    In [9]: result 
    Out[9]: False

    2.1、多个值符合条件判断
    常规写法:

    status_code = 0
    if status_code == -1 or status_code == -2 or status_code == -3:
    print('fail')
    else:
    print('success')

    优雅写法:

    status_code = 0
    if status_code in [-1, -2, -3]:
    print('fail')
    else:
    print('success')

    2.2、判断是否为空
    常规写法:

    A, B, C = [1, 2, 3], {}, ''
    if len(A) > 0:
    print('A非空')
    if len(B) > 0:
    print('B非空')
    if len(C) > 0:
    print('C非空')

    优雅写法:

    A, B, C = [1, 2, 3], {}, ''
    if A:
    print('A非空')
    if B:
    print('B非空')
    if C:
    print('C非空')
    

    2.3多条件判断至少一个成立
    常规写法:

    math, english, computer = 30, 90, 80
    if math < 60 or english < 60 or computer < 60:
    print('挂科')
    else:
    print('通过')

    优雅写法:

    math, english, computer = 30, 90, 80
    if any([math < 60, english < 60, computer < 60]):
    print('挂科')
    else:
    print('通过')

    2.4:多条件判断内容全部成立
    常规写法:

    math, english, computer = 70, 90, 80
    if math > 60 and english > 60 and computer > 60:
    print('通过')
    else:
    print('挂科')
    

    优雅写法:

    math, english, computer = 70, 90, 80
    if all([math > 60, english > 60, computer > 60]):
    print('通过')
    else:
    print('挂科')

    3.使用三元操作符来进行条件赋值
    三元操作符是 if-else 语句也就是条件操作符的一个快捷方式:

    [表达式为真的返回值] if [表达式] else [表达式为假的返回值]
    这里给出几个你可以用来使代码紧凑简洁的例子。下面的语句是说“如果 y 是 9,给 x 赋值 10,不然赋值为 20”。如果需要的话我们也可以延长这条操作链。

    [on_true] if [expression] else [on_false]
    x = 10 if (y == 9) else 20

    同样地,我们可以对类做这种操作:

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

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

    下面是另一个多个条件表达式链接起来用以计算最小值的例子:

    In [10]: def small(a,b,c):
    ...: return a if a<=b and a<=c else ( b if b<=a and b<=c else c) 
    ...: 
    
    In [11]: small(1,0,1)
    Out[11]: 0
    
    In [12]: small(1,2,3)
    Out[12]: 1
    我们甚至可以在列表推导中使用三元运算符:
    
    
    In [14]: [ m**2 if m > 10 else m**4 for m in range(20) ] 
    Out[14]: 
    [0,1,16,81,256,625,1296,2401,4096,6561,10000,121,144,169,196,225,256,289,324,61] 

    4.多行字符串
    基本的方式是使用源于 C 语言的反斜杠:

    In [20]: multistr = " select * from multi_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 
    where row_id < 5'

    上面方法共有的问题是缺少合适的缩进,如果我们尝试缩进会在字符串中插入空格。所以最后的解决方案是将字符串分为多行并且将整个字符串包含在括号中:

    In [25]: multistr = ("select * from multi_row "
    ...: "where row_id < 5 " 
    ...: "order by 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) 
    1 2 3

    6.打印引入模块的文件路径
    如果你想知道引用到代码中模块的绝对路径,可以使用下面的技巧:

    In [30]: import threading 
    
    In [31]: import socket 
    
    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.交互环境下的"_"操作符
    这是一个我们大多数人不知道的有用特性,在 Python 控制台,不论何时我们测试一个表达式或者调用一个方法,结果都会分配给一个临时变量: _(一个下划线)。

    In [34]: 2 + 3 
    Out[34]: 5
    
    In [35]: _
    Out[35]: 5
    
    In [36]: print(_) 
    5

    8.这是一个非常有用的功能,可惜很少人知道。

    当你在交互界面敲代码,获得一个临时结果,却没有用变量名去保存它的时候,可以用"_"来获取最近一次临时结果

    “_” 是上一个执行的表达式的输出。

    8.字典/集合推导式
    与我们使用的列表推导相似,我们也可以使用字典/集合推导,它们使用起来简单且有效,下面是一个例子:

    In [37]: testDict = {i : i*i for i in range(5)} 
    
    In [38]: testSet = { i*2 for i in range(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}

    配合enumerate:
    iterable=[1,2,4,5,2]
    set={i:item for (i,item) in enumerate(iterable)}
    print(set) //{0: 1, 1: 2, 2: 4, 3: 5, 4: 2}

    注:两个语句中只有一个 <:> 的不同,另,在 Python3 中运行上述代码时,将 <xrange> 改为 <range>。

    9.调试脚本
    我们可以在 <pdb> 模块的帮助下在 Python 脚本中设置断点,下面是一个例子:

    import pdb
    pdb.set_trace()

    我们可以在脚本中任何位置指定 <pdb.set_trace()> 并且在那里设置一个断点,相当简便。

    10.开启文件分享
    Python 允许运行一个 HTTP 服务器来从根路径共享文件,下面是开启服务器的命令:(python3环境)

    python3 -m http.server

    上面的命令会在默认端口也就是 8000 开启一个服务器,你可以将一个自定义的端口号以最后一个参数的方式传递到上面的命令中。

    Paste_Image.png

    11.检查Python中的对象
    我们可以通过调用 dir() 方法来检查 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语句
    我们可以使用下面的方式来验证多个值:

    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 版本:

    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.5n")
    print("Please upgrade to 3.5.n")
    sys.exit(1)
    
    #Print Python version in a readable format.
    print("Current Python version: ", sys.version)
    

      


    或者你可以使用 sys.version_info >= (3, 5) 来替换上面代码中的 sys.hexversion != 50660080,这是一个读者的建议。

    python3运行结果:

    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.组合多个字符串
    如果你想拼接列表中的所有记号,比如下面的例子:

    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]: for element in reversed([1,3,5]):
    ...: print(element) 
    ...: 
    5
    3
    1
    

      


    一行代码翻转字符串

    In [53]: "Test Python"[::-1]
    Out[53]: 'nohtyP tseT'
    

      


    使用切片翻转列表

    [1, 3, 5][::-1]
    

      


    16.玩转枚举
    使用枚举可以在循环中方便地找到(当前的)索引:

    In [54]: testList= [10,20,30] 
    
    In [55]: for i,value in enumerate(testList):
    ...: print(i,':',value)
    ...: 
    0 : 10
    1 : 20
    2 : 30
    

      


    17.在python中使用枚举量
    我们可以使用下面的方式来定义枚举量:

    In [56]: class Shapes:
    ...: Circle,Square,Triangle,Quadrangle = range(4) 
    ...: 
    
    In [57]: Shapes.Circle
    Out[57]: 0
    
    In [58]: Shapes.Square
    Out[58]: 1
    
    In [59]: Shapes.Triangle
    Out[59]: 2
    
    In [60]: Shapes.Quadrangle
    Out[60]: 3
    

      


    18.从方法中返回多个值
    并没有太多编程语言支持这个特性,然而 Python 中的方法确实(可以)返回多个值,请参见下面的例子来看看这是如何工作的:

    In [61]: def x():
    ...: return 1,2,3,4 
    ...: 
    
    In [62]: a,b,c,d = x()
    
    In [63]: print(a,b,c,d) 
    1 2 3 4
    

      


    20.使用字典来存储选择操作
    我们能构造一个字典来存储表达式:

    In [70]: stdacl = { 
    ...: 'sum':lambda x,y : x + y,
    ...: 'subtract':lambda x,y : x - y 
    ...: } 
    
    
    In [73]: stdacl['sum'](9,3) 
    Out[73]: 12
    
    In [74]: stdacl['subtract'](9,3) 
    Out[74]: 6
    

      


    21.一行代码计算任何数的阶乘
    python3环境:

    In [75]: import functools
    
    In [76]: result = ( lambda k : functools.reduce(int.__mul__,range(1,k+1),1))(3) 
    
    In [77]: result
    Out[77]: 6

    22.找到列表中出现最频繁的数

    In [82]: test = [1,2,3,4,2,2,3,1,4,4,4] 
    
    In [83]: 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-> 100

    谨慎修改

    24.检查一个对象的内存使用
    在 Python 2.7 中,一个 32 比特的整数占用 24 字节,在 Python 3.5 中利用 28 字节。为确定内存使用,我们可以调用 getsizeof 方法:

    python2.7:
    
    import sys
    x=1
    print(sys.getsizeof(x))
    
    #-> 24
    python3:
    
    In [86]: import sys 
    
    In [87]: x = 1
    
    In [88]: sys.getsizeof(x) 
    Out[88]: 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

    很明显,你可以从结果中看到确实有内存使用上的节省,但是你只应该在一个类的内存开销不必要得大时才使用 slots。只在对应用进行性能分析后才使用它,不然地话,你只是使得代码难以改变而没有真正的益处。

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

    In [89]: import sys 
    
    In [90]: lprint = lambda *args: sys.stdout.write("".join(map(str,args))) 
    
    In [91]: lprint("python","tips",1000,1001) 
    Out[91]: pythontips1000100118
    27.从两个相关的序列构建一个字典
    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}

    28.一行代码搜索字符串的多个前后缀

    In [95]: print("http://www.google.com".startswith(("http://", "https://")))
    True
    
    In [96]: print("http://www.google.co.uk".endswith((".com", ".co.uk")))
    True

    29. 不使用循环构造一个列表

    In [101]: test = [[-1, -2], [30, 40], [25, 35]] 
    
    In [102]: import itertools
    
    In [103]: print(list(itertools.chain.from_iterable(test)))
    [-1, -2, 30, 40, 25, 35]

    30.在Python中实现一个真正的switch-case语句
    下面的代码使用一个字典来模拟构造一个switch-case。

    In [104]: def xswitch(x):
    ...: return xswitch._system_dict.get(x, None) 
    ...: 
    
    In [105]: xswitch._system_dict = {'files': 10, 'folders': 5, 'devices': 2}
    
    In [106]: print(xswitch('default'))
    None
    
    In [107]: print(xswitch('devices'))

    作者:海贼之路飞
    链接:https://www.jianshu.com/p/cdceff697af8

    31

    强制浮点数除法

    如果我们除以一个整数,即使结果是一个浮点数,Python(2) 依旧会给我们一个整数。为了规避这个问题,我们需要这样做:

    result = 1.0/2

    但是现在有一种别的方法可以解决这个问题,甚至在之前我都没有意识到有这种方法存在。你可以进行如下操作:

    from __future__ import division
     
    result = 1/2
     
    # print(result)
     
    # 0.5

    需要注意的是这个窍门只适用于Python 2。在Python 3 中就不需要进行import 操作了,因为它已经默认进行import了。

    列表推导式

    常规写法:

    nums = []
    for i in range(10):
    nums.append(i)
    print(nums)
    # output: 
    # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    优雅写法:

    nums = [i for i in range(10)]
    print(nums)
    # output: 
    # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    4. with - as
    with 这个词儿,英文里面不难翻译,但在 Python 语法中怎么翻译,我还真想不出来,大致上是一种上下文管理协议。作为初学者,不用关注 with 的各种方法以及机制如何,只需要了解它的应用场景就可以了。with 语句适合一些事先需要准备,事后需要处理的任务,比如,文件操作,需要先打开文件,操作完成后需要关闭文件。如果不使用with,文件操作通常得这样:

    fp = open(r"D:CSDNColumn	empmpmap.py", 'r')
    try:
    contents = fp.readlines()
    finally:
    fp.close()

    如果使用 with - as,那就优雅多了:

    with open(r"D:CSDNColumn	empmpmap.py", 'r') as fp:
    contents = fp.readlines()
    

      

    遍历字典

    d1={'sdf':22,'sdfs':'sdfs'}
    d1
     
    {'sdf': 22, 'sdfs': 'sdfs'}
     
     
    for key,value in d1.items():
        print(key,value)
     
     
    sdf 22
    sdfs sdfs
    

      

  • 相关阅读:
    配置java 环境变量(jdk)
    R语言的神奇之一--基于向量
    python绘制图形(Turtle模块)
    右键菜单中新建记事本选项丢失的解决办法
    在windows下远程访问linux服务器
    针对Chrome谷歌等浏览器不再支持showModalDialog的解决方案
    导入一个新项目需要注意的几大问题(jdk1.6+eclipse4.4+tomcat6)
    【漏洞公告】Tomcat信息泄漏和远程代码执行漏洞:CVE-2017-12615/CVE-2017-12616
    python基础篇10-py2和py3编码
    python基础篇03-range/for/break/continue/while/if
  • 原文地址:https://www.cnblogs.com/chargeworld/p/12268618.html
Copyright © 2011-2022 走看看