I want to add two numbers to the list next to each other and return the final answer in a list using python. for example my_list = [1,2,3,5,6] And the final list will be [1,3,5,8,11] for the first digit I will consider the initial value as 0.
I tried this way to get the answer
list1 = [1,2,3,0,5,6]
first_value = 0
new_list = []
for i,each_value in enumerate(list1):
if i == 0:
sum = first_value each_value
else:
sum = each_value prev_val
new_list.append(sum)
#i = i 1
prev_val = each_value
print(new_list)
I have got the output that I want but I wanted to know can we write the same code with less number of lines either by using lambda or some python collection.
CodePudding user response:
Try this.
l = [1,2,3,5,6]
def sum_(l):
return list(map(lambda e:l[e] l[e-1] if e!=0 else l[e], range(len(l))))
print(sum_(l))
OUTPUT [1, 3, 5, 8, 11]
Explanation
I suggest After reading this you need to take a look at the map function.
I give the map function two parameters one of them is
range(len(l))
If you try to print In the above case this will output torange(0,5)
Try to transform this into the listlist(range(len(l)))
this will output[0,1,2,3,4]
.Map function is iterated through this list and set the value of e(provide this is a parameter in lambda function. You can change it to any other name.)
In line
map(lambda e:l[e] l[e-1] if e!=0 else l[e]
. Here I am matching if e is not equal to 0, Because if e is 0 then e-1 is -1 which will point to the last element of the list Which will cause the code to output the wrong output.In my code if e equals 0 then this will return lst[e] else this will return the lst[e] lst[e-1].
I hope this will explain this