简体   繁体   English

在列表中添加数字并追加到新列表

[英]Add numbers within list and append to new list

This is what I am trying to do. 这就是我想要做的。 Create a new list (addtwo) where the each element is the sum of the corresponding and previous elements in a source list (numberlist). 创建一个新列表(addtwo),其中每个元素是源列表(数字列表)中相应元素和先前元素的总和。 Obviously the first element in new list would be same as first element in source list. 显然,新列表中的第一个元素将与源列表中的第一个元素相同。

numberlist = [2, 4, 5, 1, 8, 2, 0, 1]
addtwo = [el[0] + el[1] for el in numberlist]

Produces this error message: TypeError: 'int' object has no attribute ' getitem ' 产生此错误消息:TypeError:'int'对象没有属性' getitem '

This is what the new list should look like, using the numbers in "numberlist": 使用“ numberlist”中的数字,新列表应如下所示:

[2, 6, 9, 6, 9, 10, 2, 1]

In your original attempt, el is just an integer, not a list, so trying to index it generated the error message. 在您最初的尝试中,el只是一个整数,而不是一个列表,因此尝试对其进行索引会生成错误消息。

You need to iterate over the contents of your original list, compute the sums, and then append those sums to the new list. 您需要遍历原始列表的内容,计算总和,然后将这些总和追加到新列表中。

Something like this code: 类似于以下代码:

numberlist = [2, 4, 5, 1, 8, 2, 0, 1]
newlist = []
newlist.append(numberlist[0])
for index in range(1,len(numberlist)): 
    sum = numberlist[index] + numberlist[index-1]
    newlist.append(sum)
print 'newlist', newlist

Alternative version using list comprehension, with leading element from original list is 使用列表理解的替代版本,其原始列表中的前导元素为

numberlist = [2, 4, 5, 1, 8, 2, 0, 1]
newlist_comp = [numberlist[index] + numberlist[index-1] for index in range(1,len(numberlist))]
newlist_two = numberlist[0] + newlist_comp
print 'newlist_two', newlist_two

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM