Python 将嵌套的for循环转换成map等价物

Python 将嵌套的for循环转换成map等价物

一般来说,for循环用于执行/迭代一段代码固定次数。而 嵌套的for循环 就是指,对一段代码进行x次迭代,然后在该代码内部再运行另一段代码y次。

嵌套的for循环语法

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

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

语法

map(function, iterable)

在这里,

  • function: 这个函数将被应用到可迭代对象的每个元素。

  • iterable: 一个类似于列表、集合、元组等的序列对象。

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

示例

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

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)

输出

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()函数两次替换列表推导来迭代列表和子列表元素。

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()函数找出指定范围内的所有质数的列表。

# 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等效的代码来找到给定范围内所有质数的列表。

使用lambda和if else语句块以及filter函数来实现map等效代码。

示例

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

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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程