Python代码在原始lis中创建邻域和自身的和

2024-10-01 11:33:45 发布

您现在位置:Python中文网/ 问答频道 /正文

Question: Given a list of integers, write python code to create a new list with the same number of elements as the original list such that each integer in the new list is the sum of its neighbors and itself in the original list. Example: is listA = [10,20,30,40,50], listB = [30,60,90,120,90]

我正在努力寻找正确的方法来设置这个代码。我知道如何定义函数,但是如何设置相邻整数/自身的加法?任何帮助都将不胜感激。在

到目前为止我所拥有的:

def sumNeighbors(list, start = 0, end =None):
    if end is None:
       end = len(list)

sum = 0
i = start
while i < end:
    sum += list[i]
    i += 1
return sum

text = raw_input ("Enter an integer (period to end): ")
list = []
while text != '.':
    textInt = int(text)
    list.append(textInt)
    text = raw_input("Enter an integer (period to end): ")

print "List: ", list
print "sum: ", sumNeighbors(list)

Tags: ofthetotextinnonenewis
3条回答

你需要建立一个迭代。在

>>> listA = [10,20,30,40,50]
>>> for index, item in enumerate(listA):
...   print 'I am at index {} and the current item is {}'.format(index, item)
... 
I am at index 0 and the current item is 10
I am at index 1 and the current item is 20
I am at index 2 and the current item is 30
I am at index 3 and the current item is 40
I am at index 4 and the current item is 50

现在你想在这个循环中添加一些额外的逻辑:

^{pr2}$

我只是在列表的末尾加上了特殊情况。基本上,在列表的开头,您只需要添加右邻居,而在列表的末尾,您只需要添加左邻居。在

所以,我首先附加第一项,即索引0处的值+索引1处的值。在

new_list.append(list[0] + list[1])

然后,我使用while循环遍历所有中间索引。在

对于其中的每一个,我们都在求list[x - 1] + list[x] + list[x + 1]

小心地开始用索引1而不是0来求中间值,因为0已经是特殊大小写了。然后,通过使用一个到len(list) - 1的for循环,确保您没有偏离末尾。对于最后一项,您只需求和list[x - 1] + list[x]

以下是全部代码:

def sum_neighbors(list):
    new_list = []
    new_list.append(list[0] + list[1])
    x = 1
    while x < len(list) - 1:
        new_list.append(list[x - 1] + list[x] + list[x + 1])
        x += 1
    new_list.append(list[x - 1] + list[x])

    return new_list

直接要求它:你想要一个列表,它是(从一个由0组成的列表中提取的值,后跟原始列表中除最后一个元素之外的所有元素;一个从原始列表中提取的值;以及一个由原始列表中除第一个元素外的所有元素组成的列表,后跟0)的值,从元素角度考虑。在

在Python中,它的拼写是:

[sum(z) for z in zip([0] + original[:-1], original, original[1:] + [0])]

相关问题 更多 >