Python – 列表中第k列的乘积
列表可以在方括号内包含任意数量的子列表,并用逗号分隔。一旦在方括号内定义了的元素,就无法更改。因此,我们可以在列表内部存储多个值,并减少复杂的操作。该列表可以包含元素和另一个名为子列表的列表。
在本文中,涉及将列元素相乘的过程,并为了更好地理解,让我们来举一个例子。列表包含三个子列表,每个子列表包含三个元素。程序员决定生成每个列表的最后一个元素,即索引值为2的所有元素。
List = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
将第二个索引元素相乘,即3 * 6 * 9 = 162,这是返回的乘积。同样,Python程序可以使用不同的方法来执行功能,从而提高效率并减少时间。
方法
- 方法1 – 使用for循环
-
方法2 – 使用reduce方法
方法1:使用for循环在列表的列表中生成第k列的Python程序
for循环将迭代给定的元素列表,并找到列表的列表指定索引值的乘积。
算法
- 步骤1: 定义具有两个参数的函数
-
步骤2: 使用isinstance()函数,可以检查列表中是否存在给定的输入。
-
步骤3: 在下面的代码中,将其设置为2,因此打印结果;当指定的值大于2时,执行返回语句。
-
步骤4: 然后,它检查三行,即三个列表是否具有足够且相等的列。
-
步骤5: 使用for循环计算乘积值,并存储在名为”result”的变量中。
-
步骤6: 初始化带有整数值和三个子列表的列表。
-
步骤7: 打印最终输出。
示例
#function is defined with two parameters
def product_cols(lst,cols_val):
#To check whether the input is in the given list
if not isinstance(lst,list):
raise Exception(f"object {type(file)} isn't list type")
#if loop is used to check whether all column and indexes are correct
for a,row in enumerate(lst,start=1):
try:
temp=row[cols_val]
except IndexError:
raise Exception(f"{str(a)}th given values is not within the limit{str(cols_val)}.")
# The product is calculated using for loop
result = 1
for each_row in lst:
result *= each_row[cols_val]
return result
#initializing the list element
list1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
#The final output is printed for the elements in index value of 2
print(product_cols(list1, 2))
输出
162
方法2:使用reduce()方法在列表列表中生成第k列的Python程序
这个过程可能看起来很简单,但是使用reduce方法来实现程序是件繁琐的事情。必需的模块被导入,根据给定的输入值,程序被执行。
算法
- 步骤1 - 导入所需的模块以使用reduce和operator等函数。
-
步骤2 - 将函数定义为两个参数,即列表的列表和列索引值。
-
步骤3 - 检查输入是否存在于给定列表中。
-
步骤4 - 然后检查行是否正确包含了所有的列元素。
-
步骤5 - 使用reduce函数,计算列表列表的乘积,并使用print()函数返回结果。
示例
#importing the module to use reduce function
from functools import reduce
#importing the operator
import operator
#defining the function with two parameters
def product_cols(lst,cols_val):
#To check whether the input is in the given list
if not isinstance(lst,list):
raise Exception(f"object {type(file)} isn't list type")
#if loop is used to check whether all column and indexes are correct
for a,row in enumerate(lst,start=1):
try:
temp=row[cols_val]
except IndexError:
raise Exception(f"{str(a)}the given values is not within the limit{str(cols_val)}.")
return reduce(operator.mul,[each_row[cols_val] for each_row in lst])
#initializing the list with set of sublists
list1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
#Finally printing the list after the multiplication
print(product_cols(list1, 2))
输出
162
结论
Python属于高级语言,使用Python的人可以利用简单的概念和功能找到解决问题的方法。该语言由多个数据结构组成,其中列表是最常见的一种。使用functools模块和for循环方法提供了不同的方法来打印第k列的乘积。