两个Python生成器中的常见项目 [英] Common items in two Python generators

查看:82
本文介绍了两个Python生成器中的常见项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了将其中一个读入列表之外,是否有办法在两个Python生成器中找到共同的项目?您无法承担有关物品订购的任何事情.

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.

一个不好的例子:

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?

推荐答案

如果您不能假设任何有关项目顺序的信息,那么您就不能在不将其中一个生成器完全读入(或set,如果您不关心一个生成器中的重复项,则可能更有意义).

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.

如何使用set s:

>>> 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])

这篇关于两个Python生成器中的常见项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆