黃哥Python:從Python官方文檔中挖礦之List Comprehensions

List Comprehensions 翻譯中文為列表解析。

以下內容為黃哥選自Python 官方文檔,轉載請註明來源。

下面的內容來自Python官方文檔

https://docs.python.org/zh-cn/3.8/tutorial/datastructures.html#list-comprehensions


黃哥Python:從Python官方文檔中挖礦之List Comprehensions


1、列表解析定義:

列表解析提供一種簡單的方式創建list。

List comprehensions provide a concise way to create lists

例子:

<code>>>> squares = []
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

使用列表解析是這樣的
squares = [x**2 for x in range(10)]
/<code>

2、語法形式:

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.

列表解析由中括號[],包含表達式,表達式後面跟隨著一個for 語句,for語句後面再跟隨者0個或多個for 、if語句。列表解析的結果是由表達式根據後面的for和if 共同計算出來的。

例子:

<code>>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

等同於
>>> combs = []
>>> for x in [1,2,3]:
... for y in [3,1,4]:

... if x != y:
... combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
/<code>

3、看例子學習

<code>>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a method on each element
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # create a list of 2-tuples like (number, square)
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple must be parenthesized, otherwise an error is raised
>>> [x, x**2 for x in range(6)]
File "<stdin>", line 1, in <module>
[x, x**2 for x in range(6)]
^
SyntaxError: invalid syntax
>>> # flatten a list using a listcomp with two 'for'
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
/<module>/<stdin>/<code>

4、列表解析可以包含複雜的表達式和嵌套函數。

List comprehensions can contain complex expressions and nested functions

<code>>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']/<code>

5、嵌套列表解析

Nested List Comprehensions

<code>>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]
The following list comprehension will transpose rows and columns:
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

也可以
>>> zip(*matrix)
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
/<code>


6、既然list 有這種語法,那麼字典、集合等有這樣的語法嗎?必須有啊?

<code>集合
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
set(['r', 'd'])

字典
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}/<code>

看文檔學習Python 是必須要養成的習慣,黃哥在後面繼續分享從文檔中挖掘的語法知識。


分享到:


相關文章: