技术文章和资源

技术文章(时间排序)

热门类别

Python PHP MySQL JDBC Linux

Python - 将所有交叉列表元素对相乘

pythonserver side programmingprogramming

在给定的问题陈述中,我们必须将所有交叉列表元素相乘,并使用 Python 函数创建这些产品的新列表。在某些情况下,我们必须将两个列表中的每一对项目相乘,以生成包含产品的单个列表。因此,我们将讨论以各种方式解决这一挑战的逻辑。

理解问题的逻辑

当前的问题是将给定列表的所有交叉元素相乘,并创建一个将保存这些元素的乘积的列表。为了解决这个问题,我们可以使用几种方法,例如使用嵌套循环迭代每个项目,并将每个项目相乘并将其存储在新列表中。或者我们可以通过映射两个列表的项目来使用 lambda 函数。我们也可以使用 Python 的 numpy 库来解决这个问题。那么让我们看看执行这项任务的具体方法。

方法 1 - 使用嵌套循环

算法

  • 步骤 1 - 定义执行乘法运算的函数。将其命名为 multiply_cross_items,并传递两个参数作为 sample_list1 和 sample_list2。

  • 步骤 2 - 将空白列表初始化为乘法,以保存元素对的乘积。

  • 步骤 3 - 使用嵌套循环,我们将遍历两个列表的项目。在第二个循环中,我们将计算 i 和 j 的乘积。然后将乘积附加到乘法列表中。

  • 步骤 4 - 返回乘法列表并调用输入列表和函数来打印结果。

示例

# 定义执行乘法的函数
def multiply_cross_items(sample_list1, sample_list2):
   multiplication = []
   # 嵌套 for 循环
   for i in sample_list1:
      for j in sample_list2:
         multiplication.append(i * j)
   return multiplication

# 调用列表和函数
sample_list1 = [12, 14, 15]
sample_list2 = [10, 9, 8]
Output = multiply_cross_items(sample_list1, sample_list2)
print(Output)

输出

[120, 108, 96, 140, 126, 112, 150, 135, 120]

方法 2 - 使用 lambda 函数

算法

  • 步骤 1 − 定义执行任务的方法,将其命名为 multiply_cross_items,并传递两个参数作为 sample_list1 和 sample_list2。

  • 步骤2 − 使用 map 函数,我们将迭代两个列表的每个项目,并使用 lambda 函数计算乘法,并将结果存储在输出列表中。

  • 步骤 3 − 返回输出列表并调用输入列表和函数来打印结果。

示例

# 用于乘以给定列表的函数
def multiply_cross_items(sample_list1, sample_list2):
   Output = list(
      map(lambda a: list(map(lambda b: a*b, sample_list2)), sample_list1))
   return [item for sub_list in Output for item in sub_list]

# 调用列表和函数
list1 = [7, 8, 9]
list2 = [6, 5, 4]
Output = multiply_cross_items(list1, list2)
print(Output)

输出

[42, 35, 28, 48, 40, 32, 54, 45, 36]

方法 3 - 使用 numpy

算法

  • 步骤 1 - 首先使用 import 关键字导入库 numpy。

  • 步骤 2 - 定义执行乘法运算的方法,并将函数名称指定为 multiply_cross_items,此函数将接受两个参数,即 sample_list1 和sample_list2。

  • 步骤 3 - 在函数内部,使用 numpy 转换数组中的每个列表。并将数组名称指定为 array1 和 array2。

  • 步骤 4 - 现在我们将使用另一个数组作为乘法,它将保存给定列表项目的乘积。并使用 numpy 库的外部函数,我们将计算两个列表项目的乘积。使用 flatten 函数,我们将把数组平铺成一个数组。

  • 步骤 5 - 现在使用 tolist 方法,我们将把上述结果转换为列表格式。

  • 步骤 6 - 初始化列表并调用函数查看输出。

示例

# 导入 numpy 库
import numpy as np
# 定义函数来执行任务
def multiply_cross_items(sample_list1, sample_list2):
   array1 = np.array(sample_list1)
   array2 = np.array(sample_list2)
   multiply = np.outer(array1, array2).flatten()
   return multiply.tolist()

#调用列表和函数
sample_list1 = [4, 2, 6]
sample_list2 = [8, 5, 2]
Output = multiply_cross_items(sample_list1, sample_list2)
print(Output)

输出

[32, 20, 8, 16, 10, 4, 48, 30, 12]

复杂度

将所有代码的所有交叉列表项对相乘的时间复杂度为 O(n²),因为我们要迭代两个列表的每个项来计算元素的乘积。这里 n 是列表中存在的项目数。

结论

因此,我们讨论了如何使用 Python 将所有交叉列表项对相乘。我们已经了解了逻辑和不同的算法,以 O(n²) 的时间复杂度获得所需的结果。所有代码都允许我们计算跨列表元素的乘积并使用输出创建一个新列表。


相关文章