Python 索引匹配元素乘积

Python 索引匹配元素乘积

索引匹配元素乘积指的是包含元素并分配给相应变量的两个不同列表。如果找到公共匹配项,则通过乘法筛选元素。为了解决这个问题,Python提供了一些内置函数,例如range()、len()、zip()、prod()、reduce()和lambda()。

让我们以一个例子来说明。

给定的输入列表:

list_1 = [10, 20, 30, 40]

list_2 = [10, 29, 30, 10]

因此,在索引0和2处找到了公共匹配项,其乘积为10*30 = 300。

语法

下面是示例中使用的语法。

range()

range()是Python中的一种内置函数,根据给定的范围返回数字序列。

len()

len()是Python中的内置函数,用于返回对象的长度。

zip()

内置函数

prod()

prod()是Python中的内置函数,它返回所有元素的乘积。

reduce()

reduce是Python中的一个内置方法,它遵循functools模块的方式,通过接收两个参数(函数和可迭代对象)来返回一个单一的值。

lambda()

函数 lambda 提供了一种使用lambda关键字声明简洁匿名函数的快捷方式。lambda函数只有一个表达式。

使用for循环

在下面的示例中,我们将通过在相应的变量中创建两个列表来启动程序。然后将初始值p设置为1,该值将用于具有列表元素的乘积。接下来,使用for循环通过使用内置函数len()迭代第一个输入列表。使用if语句它检查第一个索引列表是否与第二个索引列表匹配。如果找到共同的匹配,则通过乘以1来过滤这些列表元素,从而简化输出。

示例

lst1 = [10, 20, 30, 40, 50, 60]
lst2 = [10, 34, 3, 89, 7, 60]
p = 1
for i in range(len(lst1)):
    if lst1[i] == lst2[i]:
        p *= lst1[i]
print("Result of index match element Product:\n", p)

输出

Result of index match element Product:
 600

使用列表推导式和zip()函数

在下面的例子中,程序使用列表推导式,其中zip()方法将两个不同的列表合并在一起以找到相同的匹配项。如果两个列表中的共同元素匹配,则通过对这些元素进行乘积来返回过滤结果。

示例

# Using list comprehension and zip()
lst1 = [10, 20, 30, 40, 50, 60]
lst2 = [10, 34, 30, 89, 7, 60]
# Initialize the initial value of the Product
product = 1
match_item = [x for x, y in zip(lst1, lst2) if x == y]
# Using if-statement to iterate the matching element
if match_item:
    product = 1
    for element in match_item:
        product *= element
print("Result of index match element Product:\n", product)

输出

Result of index match element Product: 
 18000

使用Numpy库

在以下示例中,程序使用numpy库和对象引用np。然后创建两个列表,用于查找公共索引元素。接下来,将列表转换为相应变量的数组,该数组将用作元素的数组。现在从两个数组中找到公共索引元素,并使用prod()函数将所有公共元素相乘,并显示结果。

示例

import numpy as np
# create the list
lst1 = [10, 20, 30, 40, 50, 60]
lst2 = [10, 34, 30, 89, 50, 6]
# Convert the list into an array
arr1 = np.array(lst1)
arr2 = np.array(lst2)
# Set the condition for matching element
match_item = arr1[arr1 == arr2]
prod_idx = np.prod(match_item)
# Display the result
print("Result of index match element Product:\n", prod_idx)

输出

Result of index match element Product: 
15000

使用Functools库

pip install functools

上述要求的命令是为了安装在系统上运行基于functools的特定程序所必需的。

在下面的示例中,使用functools库启动程序,并定义名为reduce的模块,该模块将计算匹配元素的索引。然后使用列表推导式,其中zip()函数包含两个用于设置等价条件以查找公共匹配的列表。接下来,使用一些内置函数-reduce()、lambda和if-set,用于基于匹配元素的乘积设置条件。最后,显示结果。

示例

from functools import reduce
# Create the list
lst1 = [10, 20, 30, 40, 7, 60]
lst2 = [10, 34, 30, 89, 7, 60]
# Set the condition based on the matching element
matching_elements = [x for x, y in zip(lst1, lst2) if x == y]
prod_idx = reduce(lambda x, y: x * y, matching_elements) if matching_elements else 1
# display the product
print("Result of index match element Product:\n", prod_idx)

输出

Result of index match element Product: 
 126000

结论

索引匹配元素是可以使用一些特定条件和操作来过滤的常见元素,例如numpy库、functools库、列表推导和for循环。与此程序相关的一些应用包括数据分析和数据过滤。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程