广东网站建设报价如何,php网站培训班,永康市建设局网站,网站的建设方法不包括什么用列表推导式创建列表的方式更简洁。常见的用法为#xff0c;对序列或可迭代对象中的每个元素应用某种操作#xff0c;用生成的结果创建新的列表#xff1b;或用满足特定条件的元素创建子序列。
例如#xff0c;创建平方值的列表#xff1a; squares []
对序列或可迭代对象中的每个元素应用某种操作用生成的结果创建新的列表或用满足特定条件的元素创建子序列。
例如创建平方值的列表 squares []for x in range(10):
... squares.append(x**2)
...squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]注意这段代码创建或覆盖变量 x该变量在循环结束后仍然存在。下述方法可以无副作用地计算平方列表
squares list(map(lambda x: x**2, range(10)))
# 或等价于
squares [x**2 for x in range(10)]
# 这种写法更简洁、易读列表推导式的方括号内包含以下内容一个表达式后面为一个 for 子句然后是零个或多个 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)]注意上面两段代码中for 和 if 的顺序相同。 表达式是元组例如上例的 (x, y)时必须加上括号 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 elementfreshfruit [ 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[x, x**2 for x in range(6)]^^^^^^^
SyntaxError: did you forget parentheses around the comprehension target?# flatten a list using a listcomp with two forvec [[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]列表推导式可以使用复杂的表达式和嵌套函数 from math import pi[str(round(pi, i)) for i in range(1, 6)]
[3.1, 3.14, 3.142, 3.1416, 3.14159]