I'm still a little hazy on the concept of generators. I want to make a generator function that takes in two arrays of numbers and adds the values at the corresponding indexes. I've got something that works, I'm just not sure if I'm properly doing this with lazy evaluation (ie properly using the generator). Can someone tell me if this is indeed the correct way to use the generator, or correct me if I'm doing it wrong?
def add(a1,a2):
i = 0
while i < len(a1):
yield a1[i]+a2[i]
i += 1
Yes that is a perfectly good generator. Are you sure add
is a good name for it?
zip
helps you to write this more succinctly
def add(a1, a2):
for i,j in zip(a1, a2):
yield i*j
you can also inline the generator as a generator expression
(i*j for i,j in zip(a1, a2))
If you are using Python2 you should use itertools.izip
instead of zip
because zip
isn't lazy in Python2
You could do it without the index like so:
from itertools import izip
def mult(list1, list2):
for item1, item2 in izip(list1, list2):
yield item1 + item2
In Python 3 you don't need the import
and can just use zip()
, as zip()
is lazy in Python 3.
But yes, the way you have it is the general idea.
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.