2

I am trying to multiply each one of the elements in ranking with it's "corresponding" in no_of_photos, like this:

ranking = [12,4,5,1]
no_of_photos = [25,22,11,9]

i=0

for x in ranking:
    print x * no_of_photos[i]
    i+=1

How could I do that using list comprehension and increment i ex:

a  = [x * no_of_photos[i++] for x in ranking]  

Have tried several but no luck, any suggestions?

2 Answers2

3

use zip

a = [r*n for r,n in zip(ranking, no_of_photos)]
jf328
  • 6,841
  • 10
  • 58
  • 82
2

An alternative to a list comprehension.

import operator

a = map(operator.mul, ranking, no_of_photos)

This essentially combines the zipping with the iteration, but calling operator.mul is less efficient than using the built-in * operator.

chepner
  • 497,756
  • 71
  • 530
  • 681