2

I want to subtract the previous value from the next value in a list and finally add the out put into a dictionary.

Example:

# Original List
l= [1, 10, 25, 35, 55, 100]
# Expected Out put
nl = [9, 15, 10, 20, 45]
# another list
lst = ['col1', 'col2', 'col3', 'col4', 'col5']
# final result
result = [{'col1': 9}, {'col2': 15}, {'col3': 10}, {'col4': 20}, {'col5': 45}]
Pradeep
  • 303
  • 1
  • 5
  • 18
  • Possible duplicate of [How can I iterate through two lists in parallel in Python?](http://stackoverflow.com/questions/1663807/how-can-i-iterate-through-two-lists-in-parallel-in-python) – Two-Bit Alchemist Apr 07 '16 at 15:32
  • You'll use `zip` as stated in link to process both lists simultaneously, but instead of two lists you'll have `l` and `l[1:]` – Two-Bit Alchemist Apr 07 '16 at 15:33
  • In one line: `nl = [y-x for x,y in zip(l, l[1:])]` The 'final result' is similar: `result = [{k:v} for k, v in zip(lst, nl)] – Two-Bit Alchemist Apr 07 '16 at 15:34
  • Thanks. This is what i was looking for. did not found the other post you mentioned earlier. @Two-Bit Alchemist – Pradeep Apr 07 '16 at 15:41

1 Answers1

1

Here is what you need to do

l= [1, 10, 25, 35, 55, 100]
nl = [(n-l[i-1]) if i else n for i,n in enumerate(l)]
lst = ['col1', 'col2', 'col3', 'col4', 'col5']
final = dict(zip(lst, nl))
Out[460]: {'col1': 1, 'col2': 9, 'col3': 15, 'col4': 10, 'col5': 20}
C Panda
  • 3,297
  • 2
  • 11
  • 11