python转行系列10:各种推导式、生成器表达式

一、简介

推导式comprehensions(又称解析式),是Python的一种独有特性。推导式是可以从一个数据序列构建另一个新的数据序列的结构体。 共有三种推导,在Python2和3中都有支持:

  1. 列表(list)推导式
  2. 字典(dict)推导式
  3. 集合(set)推导式

官方对推导式的介绍为:

The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses. In this case, the elements of the new container are those that would be produced by considering each of the for or if clauses a block, nesting from left to right, and evaluating the expression to produce an element each time the innermost block is reached.

推导式由一个单独的表达式组成,表达式伴随着0个或多个for/if子句,但for子句至少有一个。在这种情况下,新容器的元素是这样生成的:将for或if子句中的每个子句视为一个块,从左到右嵌套,并计算表达式,以便在每次到达最内层的块时生成一个元素。

二、 具体语法

列表推导式[]

  • 生成一个[0,30)区间内的列表list。
>>> multiples = [i for i in range(30)]
>>> print(multiples)
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
>>>
  • 生成一个[0,30)区间内能被3整除的列表list。
>>> multiples = [i for i in range(30) if i % 3 == 0]
>>> multiples
 [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

字典推导式{}

使用字典推导式排除了key为“1”的字典元素

def Dict_comprehension_Test():
    src_dict = {
        "1": 'first',
        "2": 'second',
        "3": 'third'
    }
    exclude1_dict = {key:value for key, value in src_dict.items() if key != "1"}
    print(src_dict)
    print(exclude1_dict)

输出结果:

{'1': 'first', '2': 'second', '3': 'third'}
{'2': 'second', '3': 'third'}

集合推导式{}

def Set_comprehension_Test():
    list_src = [1,1,2]
    set_seq={i**2 for i in list_src}
    print(set_seq)
    print(type(set_seq))

输出结果:

{1, 4}
<class 'set'>

与前者的区别:

  1. 与list推导式不同,集合推导式使用符号{}(大括号)
  2. 与字典推导式不同,集合推导式没有key-value对

生成器表达式

         同样的语法,使用()---圆括号将产生一个生成器generator

>>> lista=[1,2,3,4,5,6]
>>> test_gen=(i for i in lista if i !=3 )
>>> print(test_gen)
<generator object <genexpr> at 0x028C6E70>
>>> next(test_gen)
1
>>> next(test_gen)
2
>>> test_gen.__next__()
4
>>>

使用推导式/生成器的优势

  1. 简化代码书写;
  2. 提高运行效率

如求range(0,10)内所有自然数的平方和。

  • 使用生成式的可能写法:
>>> sum_a = sum(x*x for x in range(0,10))   
>>> sum_a
285
  • 不用生成式的可能写法为:
def sum_power_ten():
    src = range(0, 10)
    sum = 0
    for i in src:
        sum += (i*i)
    print(sum)

对比:

         不用生成式的代码使用临时变量src存储range,再用for循环遍历range范围,代码比使用生成式复杂多。

猜你喜欢

转载自blog.csdn.net/zhaogang1993/article/details/89070020