📌  相关文章
📜  Python - 查找索引值的乘积并找到总和

📅  最后修改于: 2022-05-13 01:54:29.585000             🧑  作者: Mango

Python - 查找索引值的乘积并找到总和

给定一个元素列表,编写一个Python程序来执行索引和值的乘积并计算总和。

例子:

方法 #1:使用循环 + enumerate()

在这种情况下,我们使用 enumerate() 迭代每个元素及其索引并计算乘积。维护和计数器以更新计算的乘积的中间和。

Python3
# Python3 code to demonstrate working of
# Index Value Product Sum
# Using loop + enumerate()
  
# initializing list
test_list = [5, 3, 4, 9, 1, 2]
  
# printing original list
print("The original list is : " + str(test_list))
  
res = 0
for idx, ele in enumerate(test_list):
  
    # updating summation of required product
    res += (idx + 1) * ele
  
# printing result
print("The computed sum : " + str(res))


Python3
# Python3 code to demonstrate working of
# Index Value Product Sum
# Using loop + enumerate()
  
# initializing list
test_list = [5, 3, 4, 9, 1, 2]
  
# printing original list
print("The original list is : " + str(test_list))
  
# one liner to solve problem using list comprehension
res = sum([(idx + 1) * ele for idx, ele in enumerate(test_list)])
  
# printing result
print("The computed sum : " + str(res))


输出
The original list is : [5, 3, 4, 9, 1, 2]
The computed sum : 76

方法#2:使用sum() +列表推导+ enumerate()

解决这个问题的一种线性方法,在这种情况下,我们执行获取产品迭代的任务,因为列表理解和最后的求和是使用 sum() 完成的。

蟒蛇3

# Python3 code to demonstrate working of
# Index Value Product Sum
# Using loop + enumerate()
  
# initializing list
test_list = [5, 3, 4, 9, 1, 2]
  
# printing original list
print("The original list is : " + str(test_list))
  
# one liner to solve problem using list comprehension
res = sum([(idx + 1) * ele for idx, ele in enumerate(test_list)])
  
# printing result
print("The computed sum : " + str(res))
输出
The original list is : [5, 3, 4, 9, 1, 2]
The computed sum : 76