龙空技术网

黄哥Python:从Python官方文档中挖矿之List Comprehensions

跟黄哥学编程 131

前言:

如今我们对“黄哥python视频”都比较关怀,小伙伴们都想要知道一些“黄哥python视频”的相关资讯。那么小编在网摘上搜集了一些对于“黄哥python视频””的相关内容,希望我们能喜欢,姐妹们快快来学习一下吧!

List Comprehensions 翻译中文为列表解析。

以下内容为黄哥选自Python 官方文档,转载请注明来源。

下面的内容来自Python官方文档

1、列表解析定义:

列表解析提供一种简单的方式创建list。

List comprehensions provide a concise way to create lists

例子:

>>> 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)]

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][(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)]

3、看例子学习

>>> 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]

4、列表解析可以包含复杂的表达式和嵌套函数。

List comprehensions can contain complex expressions and nested functions

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

5、嵌套列表解析

Nested List Comprehensions

>>> 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)]

6、既然list 有这种语法,那么字典、集合等有这样的语法吗?必须有啊?

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

看文档学习Python 是必须要养成的习惯,黄哥在后面继续分享从文档中挖掘的语法知识。

标签: #黄哥python视频