zoukankan      html  css  js  c++  java
  • 【摘】人生苦短,每日python

    python和它的字符串拼接

    不懂效率的人,会这样拼接

    >>> s = ''
    >>> for substring in ['hello ', 'world ']:
    ...  s += substring
    ...
    >>> print(s)
    hello world
    

    python字符串是不可变的,拼接任意不可变序列都会生成一个新的序列对象。
    即是说,每拼接一次,就要重新分配个空间,所以效率极低。

    考虑效率的人,会这样拼接

    >>> s = ''.join(['hello ', 'world '])
    >>>
    >>> print(s)
    hello world
    

    join()的速度很快,但是可读性很差。

    中庸的人,会这样拼接

    >>> s = '%s%s' % ('hello ', 'world ')
    >>>
    >>> print(s)
    hello world
    

    已知字符串的数目,代码的性能也不是很重要,或者优化字符串拼接节省的开销很小时,可以试试format或%。


    python和它的枚举enumerate

    不会用枚举的人,写这样的代码:

    >>> i = 0
    >>> for e in ['one', 'two', 'three']:
    ...     print(i, e)
    ...     i += 1
    ...
    (0, 'one')
    (1, 'two')
    (2, 'three')
    

    会用枚举的人,写这样的代码:

    >>> for i, e in enumerate(['one', 'two', 'three']):
    ...     print(i,e)
    ...
    (0, 'one')
    (1, 'two')
    (2, 'three')
    

    摘自 《Python高级编程》

  • 相关阅读:
    日志框架 log4j2 全解析
    SpringMVC开发RESTful接口
    SpringMVC 进阶
    SpringMVC 参数映射与文件上传
    SSM整合
    算法分析
    SpringMVC 入门
    数据结构与算法概念
    在普通WEB项目中使用Spring
    《算法导论》——重复元素的随机化快排Optimization For RandomizedQuickSort
  • 原文地址:https://www.cnblogs.com/featherw/p/10300617.html
Copyright © 2011-2022 走看看