将嵌套 for 循环转换为 Python 中等效的 map 函数


通常,for 循环用于执行/迭代一段代码固定的次数。而嵌套 for 循环就是,迭代一段代码 x 次,然后我们需要在该代码中再运行另一段代码 y 次。

嵌套 for 循环语法

for x in sequence: for y in sequence: inner loop outer loop

map 是 Python 中一个内置函数,用于迭代序列的项目,并在对这些项目应用函数后生成结果。

语法

map(function, iterable)

其中,

  • function:此函数将应用于可迭代对象的项目。

  • iterable:一个序列对象,例如列表、集合、元组等。

在本文中,我们将了解 Python 程序如何将嵌套 for 循环转换为等效的 map 函数。

示例

让我们以一个嵌套 for 循环示例来更改二维数组元素的数据类型。然后,将 for 循环转换为等效的 map 函数。

Open Compiler
a = [['2.3','.2'],['-6.3','0.9']] print("Input:", a) for j in range(2): for i in range(2): a[i][j] = float(a[i][j]) print("Nested for-loop output",a) # Create a map equivalent to the above code a = [['2.3','.2'],['-6.3','0.9']] print("Input:", a) result = [list(map(float, subarr)) for subarr in a] print("Converted Map equivalent output:",result)

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

Input: [['2.3', '.2'], ['-6.3', '0.9']]
Nested for-loop output [[2.3, 0.2], [-6.3, 0.9]]
Input: [['2.3', '.2'], ['-6.3', '0.9']]
Converted Map equivalent output: [[2.3, 0.2], [-6.3, 0.9]]

在上面的代码块中,我们可以看到嵌套 for 循环和等效的 map 函数代码及其结果。在这里,我们将二维数组元素的数据类型从字符串更改为浮点数。

使用列表推导式和 map() 函数,我们将嵌套 for 循环转换为等效的 map 函数。

示例

此处,另一种解决上述问题的方法将利用 lambda 运算符将 float 映射到子列表。并且使用 map() 函数两次迭代列表和子列表元素,替换了列表推导式。

Open Compiler
a = [['2.3','.2'],['-6.3','0.9']] print("Input:", a) result = list(map(lambda b : list(map(float, b)), a)) print("Converted Map equivalent output:",result)

输出

Input: [['2.3', '.2'], ['-6.3', '0.9']]
Converted Map equivalent output: [[2.3, 0.2], [-6.3, 0.9]]

示例

让我们以一个示例来查找给定范围内所有素数的列表,使用嵌套 for 循环和 map() 函数。

Open Compiler
# Python program to find list of all the prime numbers within a range lower = 2 upper = 30 prime_numbers = [] for num in range(lower, upper + 1): # all prime numbers are greater than 1 if num > 1: for i in range(2, num): if (num % i) == 0: break else: prime_numbers.append(num) print("List of prime numbers using Nested for-loop:") print(prime_numbers) # find list of prime numbers using map map_resul = list(filter(None, list(map(lambda i: i if all(i%j != 0 for j in range(2, int(i ** 0.5) + 1)) else None , range(lower, upper + 1))))) print("List of prime numbers using Map equivalent to the nestesd for-loop:") print(map_resul)

输出

List of prime numbers using Nested for-loop:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
List of prime numbers using Map equivalent to the nestesd for-loop:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

我们可以看到嵌套 for 循环和等效的 map 函数代码,用于查找给定范围内的所有素数列表。

等效的 map 函数代码是通过使用带有 if else 块和 filter 函数的 lambda 实现的。

示例

在这个示例中,我们将编写嵌套 for 循环和等效的 map 函数代码来添加循环元素的 2 个整数。

Open Compiler
forloop_result = [] for a in range(1,5): for b in range(1,6): forloop_result.append(a+b) print("Nested for-loop output", forloop_result) from itertools import product result = list(map(lambda x: sum(x) , product(range(1,5), range(1,6)))) print("Converted Map equivalent output:",result)

输出

Nested for-loop output [2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9]
Converted Map equivalent output: [2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9]

此处,执行了 itertools 模块中的 product() 方法用于获取输入可迭代对象的笛卡尔积。如下所示,

[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5)]

更新于: 2023年5月30日

601 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告