[英]How to create an output list which is the sum of alternating elements from an input number_list
I'm trying to sum the even and odd-indexed elements of a list together without the use of the sum() method, but something is going wrong.我试图在不使用 sum() 方法的情况下将列表的偶数和奇数索引元素相加,但出了点问题。 I'm new to Python so help would be appreciated.
我是 Python 新手,因此不胜感激。
An example would be input number_list
as [1, 2, 3, 4] then the output list will be [4, 6], which is from the sum of the even-numbered elements 1 and 3, and the odd-numbered elements 2 and 4 from the list number_list
.一个例子是输入
number_list
作为 [1, 2, 3, 4] 然后输出列表将是 [4, 6],它来自偶数元素 1 和 3 的总和,以及奇数元素 2和 4 来自列表number_list
。 Similarly, [5, 8, 3, 2, 6, 7, 1] would have an output list of [8, 10, 9, 9, 5].类似地,[5, 8, 3, 2, 6, 7, 1] 的输出列表为 [8, 10, 9, 9, 5]。
This is my code:这是我的代码:
number_list = [2, 6, 3, 5, 9, 1, 7]
res=[0, 0, 0, 0, 0, 0]
for i in range(0, len(number_list)):
if(i % 2):
res[1] += number_list[i]
else :
res[0] += number_list[i]
print("Input List: {0}\n".format(number_list))
print("Output List: {0}\n".format(res))
I think the following is what you were going for;我认为以下是您想要的; your first attempt was definitely on target:
你的第一次尝试肯定是有针对性的:
!/usr/bin/env python3
number_list = [2, 6, 3, 5, 9, 1, 7]
i = 0
r = [0,0]
for n in number_list:
if (i % 2) == 0:
# Even
r[0] += n
else :
# Odd
r[1] += n
i += 1
print(" Input List: {0}". format(number_list))
print("Output List: {0}". format(r))
The result is:结果是:
Input List: [2, 6, 3, 5, 9, 1, 7]
Output List: [21, 12]
There are some simplifications here, namely throwing out Python nuances and just looking at iterating over a list of numbers, determining whether they are in the even or odd position (the i
index), and adding (summing) them to the base r
array.这里有一些简化,即抛弃 Python 的细微差别,只查看迭代数字列表,确定它们是在偶数还是奇数位置(
i
索引),并将它们添加(求和)到基础r
数组中。 Is this the most compact and optimized Python code you will encounter?这是您将遇到的最紧凑和优化的 Python 代码吗? No. But is it clear as to what you're trying to do - I think so.
不。但是你想做什么很清楚吗——我想是的。
Joe's answer is absolutely correct.乔的回答是绝对正确的。 However more compact answer would be..
然而,更紧凑的答案是..
r = [0,0]
for n, val in enumerate(number_list):
j = n % 2
r[j] += val
print(" Input List: {0}". format(number_list))
print("Output List: {0}". format(r))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.