zoukankan      html  css  js  c++  java
  • 关于python

    枚举

    不要这么做:

    i = 0
    for item in iterable:
        print i, item
        i += 1

    而是这样:

    for i, item in enumerate(iterable):
        print i, item

    enumerate可以接受第二个参数,例如:

    >>> list(enumerate('abc'))
    [(0, 'a'), (1, 'b'), (2, 'c')]
    >>> list(enumerate('abc', 1))
    [(1, 'a'), (2, 'b'), (3, 'c')]

    字典/集合 解析

    你可能知道列表解析,但不知道字典/集合解析。字典/集合解析简单而且高效,例如:

    my_dict = {i: i * i for i in xrange(100)}
    my_set = {i * 15 for i in xrange(100)}
    # There is only a difference of ':' in both

    强制浮点数除法

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

    result = 1.0/2

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

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

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

    简单的服务器

    你想快速简单的分享目录下的文件吗?可以这样做:

    # Python2
    python -m SimpleHTTPServer
    # Python 3
    python3 -m http.server

    这回启动一个服务器

    Python表达式求值

    我们都知道eval,但也许并不是所有人都知道literal_eval.可以这么做:

    import ast
    
    my_list = ast.literal_eval(expr)

    而不是这样:

    expr = "[1, 2, 3]"
    
    my_list = eval(expr)

    我相信对于大多数人来说这种形式是第一次看见,但是实际上这个在Python中已经存在很长时间了。

    分析脚本

    按下面的方式运行脚本,可以很简单的对其进行分析:

    python -m cProfile my_script.py

    对象自检

    在Python中,可以通过dir()来检查对象,例如:

    >>> foo = [1, 2, 3, 4]
    >>> dir(foo)
    ['__add__', '__class__', '__contains__',
    '__delattr__', '__delitem__', '__delslice__', ... ,
    'extend', 'index', 'insert', 'pop', 'remove',
    'reverse', 'sort']

    调试脚本

    你可以使用pdb模块在脚本中设置断点来调试脚本,就像这样:

    import pdb
    
    pdb.set_trace()

    你可以在脚本的任何地方加入pdb.set_trace(),该函数会在那个位置设置一个断点。超级方便。你应该多阅读pdb 函数的相关内容,因为在它里面还有很多鲜为人知的功能。

     

    简化if结构

    如果必须检查一些值,可以用

    if n in [1,4,5,6]:

    而不是用复杂的if结构:

    if n==1 or n==4 or n==5 or n==6:

    字符串/数列 逆序

    下面的方式可以快速反转一个列表:

    >>> a = [1,2,3,4]
    >>> a[::-1]
    [4, 3, 2, 1]
    # This creates a new reversed list.
    # If you want to reverse a list in place you can do:
    a.reverse()

    这种方式同样适用于字符串:

    >>> foo = "yasoob"
    >>> foo[::-1]
    'boosay'

    优雅地打印

    下面的方式pprint可以用优雅的方式打印字典和列表:

    from pprint import pprint
    
    pprint(my_dict)

    这用于字典打印是非常高效的,如果你想从文件中快速优雅的打印出json,可以这样做:

    cat file.json | python -m json.tools

     

    三元运算

    三元运算是if-else 语句的快捷操作,也被称为条件运算。这里有几个例子可以供你参考:

    [on_true] if [expression] else [on_false]
    x, y = 50, 25
    small = x if x < y else y

    除法相关

    •  求商、求余

    >>> divmod(5, 2)
    (2, 1)

    • 四舍五入

    >>> round(5/2)
    3.0

    字符串相关

    • ord()能够返回某个字符所对一个的ASCII值(是十进制的),字符a在ASCII中的值是97,空格在ASCII中也有值,是32。

      反过来,根据整数值得到相应字符,可以使用chr()。

    >>> ord('a')
    97

    >>> chr(99)
    'c'

     编码问题

    • error---'ascii' codec can't encode characters in position

    >>> import sys
    >>> sys.getdefaultencoding()
    'ascii'

    >>> sys.setdefaultencoding()

    Traceback (most recent call last):
    File "<pyshell#2>", line 1, in <module>
    sys.setdefaultencoding()
    AttributeError: 'module' object has no attribute 'setdefaultencoding'
    >>> reload(sys)
    >>> sys.setdefaultencoding('utf-8')

     "AttributeError: 'module' object has no attribute 'setdefaultencoding'"  why  ???

    /Lib/site.py#l545:

    """Append module search paths for third-party packages to sys.path."""
    * This module is automatically imported during initialization. *
    def setencoding():  
      """Set the string encoding used by the Unicode implementation.
        The default is 'ascii', but if you're willing to experiment, you can change this.
      """
      encoding = "ascii" # Default value set by _PyUnicode_Init()
    def main():
      ......  
      # Remove sys.setdefaultencoding() so that users cannot change the
      # encoding after initialization. The test for presence is needed when
      # this module is run as a script, because this code is executed twice.
      if hasattr(sys, "setdefaultencoding"):
        del sys.setdefaultencoding


    参考链接:
    (1)源码参见 https://hg.python.org/cpython/file/2.7/Lib/site.py#l545

    (2)编码问题更多可参考 http://www.the5fire.com/unicodeencodeerror-from-future.html

    (3)http://www.ido321.com/1576.html

  • 相关阅读:
    【转】几种Java序列化方式的实现
    【转】Java泛型方法
    【转】java序列化一定要应该注意的6个事项!
    [转]Android APK签名原理及方法
    [转]Android中内存占用的含义:(VSS,PSS,RSS,USS)
    红黑树的C语言实现
    Btree算法的C语言实现
    C++之迭代器失效总结
    tcpdump抓包工具用法说明
    setsockopt函数功能及参数详解
  • 原文地址:https://www.cnblogs.com/tangkaixin/p/4404668.html
Copyright © 2011-2022 走看看