如何在python中找到范围重叠? [英] How to find range overlap in python?

查看:116
本文介绍了如何在python中找到范围重叠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 中确定两个范围内哪些值重叠的最佳方法是什么?

What is the best way in Python to determine what values in two ranges overlap?

例如:

x = range(1,10)
y = range(8,20)

(The answer I am looking for would be the integers 8 and 9.)

给定一个范围 x,迭代另一个范围 y 并输出两个范围共享的所有值的最佳方法是什么?预先感谢您的帮助.

Given a range, x, what is the best way to iterate through another range, y and output all values that are shared by both ranges? Thanks in advance for the help.

作为后续,我意识到我还需要知道 x 是否与 y 重叠.我正在寻找一种方法来遍历范围列表,并在范围重叠的情况下执行许多其他操作.是否有一个简单的 True/False 语句来实现这一点?

As a follow-up, I realized that I also need to know if x does or does not overlap y. I am looking for a way to iterate through a list of ranges and and do a number of additional things with range that overlap. Is there a simple True/False statement to accomplish this?

推荐答案

尝试设置交集:

x = range(1,10)
y = range(8,20)
xs = set(x)
xs.intersection(y)   

输出:

set([8, 9])

请注意,intersection 接受任何可迭代对象作为参数(y 不需要转换为 set 以进行操作).有一个与 intersection 方法等效的运算符:& 但是,在这种情况下,它 需要设置两个参数.

Note that intersection accepts any iterable as an argument (y is not required to be converted to a set for the operation). There is an operator equivalent to the intersection method: & but, in this case, it requires both arguments to be sets.

这篇关于如何在python中找到范围重叠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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