【问题标题】:Add numbers within list and append to new list在列表中添加数字并附加到新列表
【发布时间】:2014-07-11 10:53:14
【问题描述】:

这就是我想要做的。创建一个新列表 (addtwo),其中每个元素是源列表 (numberlist) 中相应元素和先前元素的总和。显然,新列表中的第一个元素与源列表中的第一个元素相同。

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

产生此错误消息: TypeError:“int”对象没有属性“getitem

这是新列表的样子,使用“numberlist”中的数字:

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

【问题讨论】:

  • for el in numberlist 直接迭代整数,你怎么能索引到它们?

标签: list python-2.7 add


【解决方案1】:

在您最初的尝试中,el 只是一个整数,而不是列表,因此尝试对其进行索引会生成错误消息。

您需要遍历原始列表的内容,计算总和,然后 然后将这些总和附加到新列表中。

类似这样的代码:

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

使用列表理解的替代版本,原始列表中的前导元素是

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 2017-08-06
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    相关资源
    最近更新 更多