python 列表解析式

python的列表解析式只是为了解决已有问题提供新的语法

 

什么是列表解析式?

列表解析式是将一个列表转换成另一个列表的工具。在转换过程中,可以指定元素必须符合一定的条件,才能添加至新的列表中,这样每个元素都可以按需要进行转换。

 

可以把列表解析式看作为结合了filter函数与map函数功能的语法糖

doubled_odds = map(lambda n: n * 2, filter(lambda n: n % 2 == 1, numbers))
doubled_odds = [n * 2 for n in numbers if n % 2 == 1]

 

每个列表解析式都可以重写为for循环,但不是每个for循环都能重写为列表解析式。

:::python
new_things = []
for ITEM in old_things:
    if condition_based_on(ITEM):
        new_things.append("something with " + ITEM)

你可以将上面的for循环改写成这样的列表解析式:

:::python
new_things = ["something with " + ITEM for ITEM in old_things if condition_based_on(ITEM)]

 

如果要在列表解析式中处理嵌套循环,请记住for循环子句的顺序与我们原来for循环的顺序是一致的

:::python
flattened = []
for row in matrix:
    for n in row:
        flattened.append(n)

下面这个列表解析式实现了相同的功能:

:::python
flattened = [n for row in matrix for n in row]

 

注意可读性

如果较长的列表解析式写成一行代码,那么阅读起来就非常困难。

不过,还好Python支持在括号和花括号之间断行。

列表解析式 List comprehension
断行前:

:::python
doubled_odds = [n * 2 for n in numbers if n % 2 == 1]

断行后:

:::python
doubled_odds = [
    n * 2
    for n in numbers
    if n % 2 == 1
]

 参考https://codingpy.com/article/python-list-comprehensions-explained-visually/

posted @ 2019-10-12 11:39  Operater  阅读(892)  评论(0编辑  收藏  举报