Common items in two Python generators

会有一股神秘感。 提交于 2019-12-24 11:35:57

问题


Is there a way to find common items in two Python generators, besides reading one into a list? You can't assume anything about the ordering of the items.

As a bad example:

import random
a = (random.randint(1, 50000) for _ in xrange(300))
b = (random.randint(3500, 3700) for _ in xrange(50))      

# do A and B have any elements in common?

回答1:


If you can't assume anything about the order of the items, then you can't logically do this without reading one of the generators entirely into a list (or a set which might make more sense if you don't care about duplicates within one generator).

To illustrate this, let's assume that the only two identical elements were the first item of the one generator and the last item of the other generator (but you don't know which is which). You need to have exhausted one of the generators entirely to make sure you know which common elements there are.

How to do it with sets:

>>> import random
>>> a = (random.randint(1, 50000) for _ in xrange(300))
>>> b = (random.randint(3500, 3700) for _ in xrange(50))
>>> set(a).intersection(set(b))
set([])
>>> a = (random.randint(1, 50000) for _ in xrange(300))
>>> b = (random.randint(3500, 3700) for _ in xrange(50))
>>> set(a).intersection(set(b))
set([3634])


来源:https://stackoverflow.com/questions/9025419/common-items-in-two-python-generators

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!