列表推导式

常用写法

  1. 单层循环

             ```python
    

    [x * x for x in range(1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

             ```
    
             ```python
    

    d = {'x': 'A', 'y': 'B', 'z': 'C' } [k + '=' + v for k, v in d.iteritems()] ['y=B', 'x=A', 'z=C']

             ```
    
  2. 双层循环

             ```python
    

    [m + n for m in 'ABC' for n in 'XYZ'] ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

             ```
    
  3. 循环 + 条件判断

             ```python
    

    [x * x for x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100]

             ```
    

一些写法上的格式

Harmful

comment_ids = (featured_comment_ids + [i.id for i in all_comments.result if i.id not in featured_comment_ids])

Idiomatic

comment_ids = [comment_id 
                for comment_id in comment_ids
                if comment_id not in collapsed_comment_ids]

例如:

  • 使用列表推导式、字典推导式等来提高编码效率:

results matching ""

    No results matching ""