📜  Python – 索引值求和列表

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

Python – 索引值求和列表

要访问列表的元素,有多种方法。但有时我们可能需要访问元素以及找到它的索引并计算其总和,为此我们可能需要采用不同的策略。本文讨论了其中一些策略。

方法一:朴素的方法
这是最通用的方法,可用于执行访问索引和列表元素值的任务。这是使用循环完成的。执行求和的任务是使用外部变量相加来执行的。

# Python 3 code to demonstrate 
# Index Value Summation List
# using naive method
  
# initializing list
test_list = [1, 4, 5, 6, 7]
  
# Printing list 
print ("The original list is : " + str(test_list))
  
# using naive method to
# Index Value Summation List
res = []
for i in range(len(test_list)):
    res.append(i + test_list[i])
  
print ("The list index-value summation is : " + str(res))
输出 :
The original list is : [1, 4, 5, 6, 7]
The list index-value summation is : [1, 5, 7, 9, 11]

方法 2:使用列表理解 + sum()
此方法的工作方式与上述方法类似,但使用了列表理解技术,这减少了可能要编写的代码行数,从而节省了时间。求和的任务由 sum() 完成。

# Python 3 code to demonstrate 
# Index Value Summation List
# using list comprehension
  
# initializing list
test_list = [1, 4, 5, 6, 7]
  
# Printing list 
print ("The original list is : " + str(test_list))
  
# using list comprehension to
# Index Value Summation List
res = [sum(list((i, test_list[i]))) for i in range(len(test_list))]
  
print ("The list index-value summation is : " + str(res))
输出 :
The original list is : [1, 4, 5, 6, 7]
The list index-value summation is : [1, 5, 7, 9, 11]