標籤:

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

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

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

下面的內容來自Python官方文檔5. Data Structures

1、列表解析定義:

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

List comprehensions provide a concise way to create lists

例子:

>>> squares = []n>>> for x in range(10):n... squares.append(x**2)n...n>>> squaresn[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]nn使用列表解析是這樣的nsquares = [x**2 for x in range(10)]n

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 共同計算出來的。

例子:

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]n[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]nn等同於n>>> combs = []n>>> for x in [1,2,3]:n... for y in [3,1,4]:n... if x != y:n... combs.append((x, y))n...n>>> combsn[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]n

3、看例子學習

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

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

List comprehensions can contain complex expressions and nested functions

>>> from math import pin>>> [str(round(pi, i)) for i in range(1, 6)]n[3.1, 3.14, 3.142, 3.1416, 3.14159]n

5、嵌套列表解析

Nested List Comprehensions

>>> matrix = [n... [1, 2, 3, 4],n... [5, 6, 7, 8],n... [9, 10, 11, 12],n... ]nThe following list comprehension will transpose rows and columns:n>>> [[row[i] for row in matrix] for i in range(4)]n[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]nn也可以n>>> zip(*matrix)n[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]n

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

集合n>>> a = {x for x in abracadabra if x not in abc}n>>> anset([r, d])nn字典n>>> {x: x**2 for x in (2, 4, 6)}n{2: 4, 4: 16, 6: 36}n

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

部分免費python免費視頻

pythonpeixun/article

216小時學會python

pythonpeixun/article


推薦閱讀:

TAG:Python |