【问题标题】:How to add 2 elements in a list and put the summation of each 2 elements into another list如何在列表中添加 2 个元素并将每 2 个元素的总和放入另一个列表
【发布时间】:2020-02-11 20:41:59
【问题描述】:

我正在尝试让用户输入 num_list 然后创建 sum_list 以将 num_list 中的每 2 个元素添加到一个新列表中

sum_list[0] = num_list[0]
sum_list[1] = num_list[0] + num_list[1] 

等等

我最初尝试使用 num_list[0] 创建 sum_list,然后从 num_list 添加 n 个元素

n = int(input('Enter number of elements : ')) 



for num in range(0, n): 
    element = float(input('Enter your elements: ')) 
    num_list.append(element) 

sum_list = num_list[0]

for number in range(len(num_list)):
    sum_list[0:n] = sum_list + num_list[n]

但是,当我执行程序时,我得到了 IndexError: list index out of range

【问题讨论】:

    标签: python-2.7 list nested-lists


    【解决方案1】:

    使用enumerate

    例如:

    n = int(input('Enter number of elements : ')) 
    
    num_list = []
    for num in range(0, n): 
        element = float(input('Enter your elements: ')) 
        num_list.append(element) 
    
    sum_list = [num_list[0]]
    
    for idx, number in enumerate(num_list[1:], 1):
        sum_list.append(number + num_list[idx-1])
    print(sum_list)
    

    【讨论】:

      【解决方案2】:

      循环通过num_list 直到倒数第二个元素,并在循环时添加连续元素。

      sum_list=[num_list[0]]
      
      for i in range(len(num_list)-1):
          sum_list.append(num_list[i]+num_list[i+1])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-21
        • 2013-09-13
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多