python - 从更大的范围中减去范围 [英] python - subtracting ranges from bigger ranges
问题描述
我的问题是,我基本上想找出 BGP 聚合地址(例如:10.76.32.0 255.255.240.0
)和所有网络命令之间是否有任何空闲子网相同的路由器(例如:10.76.32.0 255.255.255.0, 10.76.33.0 255.255.255.0
)
The problem I have is that I basically would like to find if there are any free subnets between a BGP aggregate-address (ex: 10.76.32.0 255.255.240.0
) and all the network commands on the same router (ex: 10.76.32.0 255.255.255.0, 10.76.33.0 255.255.255.0
)
在上面的例子中,10.76.34.0
-> 10.76.47.255
是免费的.
In the above example, 10.76.34.0
-> 10.76.47.255
would be free.
我正在考虑通过将 IP 地址和子网掩码转换为二进制并以这种方式相减来解决这个问题.
I'm thinking of tackling this problem by converting the IP addresses and subnet masks to binary and subtracting that way.
为了简单起见,我将这个例子保留为十进制,但这样做会给我带来以下问题:假设我有一个从 1 到 250 的范围,我从中减去一个从 20 到 23 的较小范围,我想以 1 到 19 和 24 到 250 的范围结束.
To keep it simple I will keep this example in decimal but doing this would leave me with the following problem: let's say I have a range from 1 to 250, I subtract from this a smaller range that goes from 20 to 23, I would like to end up with a range from 1 to 19 and 24 to 250.
使用 range 命令并没有真正给我预期的结果,虽然我可能会创建一个包含范围内每个项目的列表并减去另一个包含项目子集的列表,但在我看来它可能不会拥有可能包含数万个元素的列表是个好主意.
Using the range command doesn't really give me the expected results and while I could possibly create a list with every item in the range and subtract another list with a sub-set of items, it seems to me that it might not be a good idea to have lists with possibly tens of thousands of elements.
荣誉
推荐答案
如果您想创建一个有间隙的范围",即 1-9 和 24-250,您可以尝试使用 filterfalse
(或 ifilterfalse
(如果您使用的是 Python 2.X)来自 itertools
模块,其中将谓词和序列作为其参数,并返回谓词返回 False
的序列元素.例如,如果您这样做:
If you are trying to create a "range" with a gap in it, i.e., with 1-9 and 24-250, you could try to use filterfalse
(or ifilterfalse
if you are using Python 2.X) from the itertools
module, which takes as its arguments a predicate and a sequence, and returns elements of the sequence where the predicate returns False
. As an example, if you do:
from itertools import filterfalse
new_range = filterfalse(lambda x: 20 <= x <= 23, range(1,251))
new_range
将是一个包含数字 1-19 和 24-250 的可迭代对象,其用法与 range()
类似:
new_range
will be an iterable containing the numbers 1-19, and 24-250, which can be used similarly to range()
:
for i in new_range:
do_things()
这篇关于python - 从更大的范围中减去范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!