私信  •  关注

lmiguelvargasf

lmiguelvargasf 最近创建的主题
lmiguelvargasf 最近回复了
6 年前
回复了 lmiguelvargasf 创建的主题 » 何时在python中使用map()[重复]

我认为最变态的方法是使用列表理解而不是 map filter . 原因是列表理解比 地图 滤波器 .

In [1]: odd_cubes = [x ** 3 for x in range(10) if x % 2 == 1] # using a list comprehension

In [2]: odd_cubes_alt = list(map(lambda x: x ** 3, filter(lambda x: x % 2 == 1, range(10)))) # using map and filter

In [3]: odd_cubes == odd_cubes_alt
Out[3]: True

如你所见,理解并不需要额外的 lambda 表达式为 地图 需要。此外,理解还可以方便地过滤,而 地图 要求 滤波器 允许过滤。