-1

I have two JSON arrays , I need to get the modulus difference of the JSON object keys. My array list can have 1000s of elements. How to calculate it efficiently? Is there a way to do it parallelly without using loop?

For example

js1 = [{'myVal':100},{'myVal':200}]
js2 = [{'myVal':500},{'myVal':800}]

Result should be :

[{'myVal':400},{'myVal':600}]
Varuni N R
  • 802
  • 3
  • 11
  • 31

1 Answers1

1

There is 2 way to acheive it :

  • Using map
js1 = [{'myVal':100},{'myVal':200}]
js2 = [{'myVal':500},{'myVal':800}]  
result = list(map(lambda x, y: {'myVal': y['myVal'] - x['myVal']}, js1, js2))
print(result)
  • Using list comprehension
js1 = [{'myVal':100},{'myVal':200}]
js2 = [{'myVal':500},{'myVal':800}]
result = [{'myVal': y['myVal'] - x['myVal']} for x,y in zip(js1,js2)]
print(result)

They will both output

[{'myVal': 400}, {'myVal': 600}]
executable
  • 3,365
  • 6
  • 24
  • 52
  • executable -- Does number of objects and keys affect the performance in this? Which one is better out of two? How do i exactly check it? – Varuni N R Jan 25 '23 at 13:17
  • `map` or list comprehension is more efficient than using a loop, as it allows the calculations to be performed in parallel. The one you're more comfortable with – executable Jan 25 '23 at 13:18
  • What do you mean, "allows the calculations to be performed in parallel"? There won't be any implicit multi-threaded execution here, no. Each `-` operation will still be performed one after the other. – deceze Jan 25 '23 at 13:31
  • I mean, the calculation is operating on both array – executable Jan 25 '23 at 13:32