列表推导式是在 Python 中定义和创建列表的一种优雅方式。我们可以像数学语句一样创建列表,并且仅在一行中。列表推导的语法更容易掌握。
列表理解通常由以下部分组成:
- 输出表达式;
- 输入序列;
- 表示输入序列成员的变量;
- 一个可选的谓词部分;
列表推导的语法:
List = [expression(i) for i in another_list if filter(i)]
示例代码:
lst = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print(lst)
运行结果如下:
[1, 9, 25, 49, 81]
在上面的例子中,
x ** 2
是表达式。range (1, 11)
是一个输入序列或另一个列表。x
是变量。- 如果
x % 2 == 1
是谓词部分。
什么是 lambda?
在 Python 中,匿名函数意味着函数没有名称。我们已经知道 def
关键字用于定义普通函数,而 lambda 关键字用于创建匿名函数。它具有以下语法:
lambda 的语法:
lambda arguments : expression
示例代码:
lst = list(map(lambda x: x**2, range(1, 5)))
print(lst)
运行结果:
[1, 4, 9, 16]
Lambda 和 列表推导式的区别
列表推导式用于创建列表,Lambda 是可以像其他函数一样处理并因此返回值或列表的函数。
例子:
# list from range 0 to 10
list_ = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list_)
# lambda function
lambda_list = list(map(lambda x: x * 2, list_))
# Map basically iterates every element
# in the list_ and returns the lambda
# function result
print(lambda_list)
# list comprehension
list_comp = [x * 2 for x in list_]
print(list_comp)
运行结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
列表理解与 lambda + 过滤器的图形表示
从图中我们可以看出,整体列表理解比过滤函数快得多。过滤器仅对小列表更快。
import numpy as np
import matplotlib.pyplot as plt
import time
# Compare runtime of both methods
sizes = [i * 10000 for i in range(100)]
filter_runtimes = []
list_comp_runtimes = []
for lis_size in sizes:
lst = list(range(lis_size))
# Get time stamps
time_A = time.time()
list(filter(lambda x: x % 2, lst))
time_B = time.time()
[x for x in lst if x % 2]
time_C = time.time()
# Calculate runtimes
filter_runtimes.append((lis_size, time_B - time_A))
list_comp_runtimes.append((lis_size, time_C - time_B))
# list comprehension vs. lambda + filter using Matplotlib
filt = np.array(filter_runtimes)
lis = np.array(list_comp_runtimes)
plt.plot(filt[:, 0], filt[:, 1], label='filter')
plt.plot(lis[:, 0], lis[:, 1], label='list comprehension')
plt.xlabel('list size')
plt.ylabel('runtime in seconds)')
plt.legend()
plt.show()
运行结果:
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/276166.html