I am trying to iterate over all numbers in my list and I want to sum each number with his neighbor.
DataList=[2,7,18,22]
total=0
for number in DataList:
total+=number
print(DataList[0] + DataList[1])
print(DataList[0] + DataList[1]+DataList[2])
print(DataList[1] + DataList[2]+DataList[3])
print(DataList[2] + DataList[3])
#Output from code above
9
27
47
40
As you can see from code above I already made some solution but this solution is not good (in realistic I have very big sample) because I typed all commands with print, so can anybody help me how to solve this problem and make automatic loop and make sum over all neighbors numbers?
Simply use a mix of if-elif-else
with loop as:
DataList=[2,7,18,22]
for i in range(len(DataList)):
if i == 0:
print(DataList[i] + DataList[i+1])
elif i == len(DataList)-1:
print(DataList[i-1] + DataList[i])
else:
print(DataList[i-1] + DataList[i] + DataList[i+1])
There is a function in itertools which is accumulate it is actually functioning as you want. This is the python docs you can find accumulate here https://docs.python.org/3/library/itertools.html
DataList=[2,7,18,22]
xp=[items for item in [[sum(DataList[:x+1]),sum(DataList[x:])]for x in range(len(DataList))] for items in item]
print(xp)
I think this is what you intend to have:
totalNum = len(DataList)
totalSum = 0
sumArray = [0]*totalNum
for i in range(totalNum):
sumArray[i] += DataList[i]
if i+1 < totalNum:
sumArray[i] += DataList[i+1]
if i-1 > 0:
sumArray[i] += DataList[i-1]
for i in range(totalNum):
print(sumArray[i])
A "clever" way to do it would be to create three versions of the list with 0
's appended, them sum them up.
DataList = [ 2, 7, 18, 22 ]
l = [ 0, 0 ] + DataList
c = [ 0 ] + DataList + [ 0 ]
r = DataList + [ 0, 0 ]
sums = [ sum( n ) for n in zip( l, c, r ) ]
You can then slice the elements off the ends if you don't want them.
Using this approach you can also use numpy
to speed of the calculation for large lists.
sums = np.sum( np.array( [ l, c, r ] ), axis = 0 )
For different sized lists you can see the numpy
payoff (note y-axis is in log scale)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.