查找包含在python中排除范围的范围内的范围

时间:2015-10-03 21:06:14

标签: python

我有一个范围说(0,1000)。 我的另一个输入将被排除范围[(200,400),(600,800)]。 我需要输出包括范围[(0,199),(401,599),(801,1000)]。

如何在python中实现它?

3 个答案:

答案 0 :(得分:2)

你可以chain iterables一起:

from itertools import chain

for i in chain(range(1,200), range(401, 600), range(801, 1001)):
    # etc

此外,如果您已获得范围并且只能迭代一次,则可以使用teeislice

def excluded(sequence):
    first, second, third = tee(sequence, 3)
    yield from chain(islice(first, 1, 200),
                     islice(second, 401, 600),
                     islice(third, 801, 1001))

for i in excluded(range(0, 1000)):
    # etc.

答案 1 :(得分:1)

如果你想要元组,这个

def exclude_ranges(to, exc):
    cur = 0
    res = []
    for ef, et in exc:
        res.append((cur, ef-1))
        cur = et + 1
    res.append((cur, to))
    return res

exc = [(200, 400), (600, 800)]
ranges = exclude_ranges(1000, exc)
print ranges

产生

[(0, 199), (401, 599), (801, 1000)]

如下所示,将其作为发电机可能是值得的:

def exclude_ranges(to, exc):
    cur = 0
    res = []
    for ef, et in exc:
        yield cur, ef-1
        cur = et + 1
    yield cur, to

exc = [(200, 400), (600, 800)]
ranges = exclude_ranges(1000, exc)
print list(ranges) # or for i in ranges: print i

答案 2 :(得分:0)

exclude_ranges = [range(200, 400), range(600, 800)]
# convert the ranges to sets for quick lookup
exclude_ranges = [set(er) for er in exclude_ranges]

for x in range(1000):
    if any(x in er for er in exclude_ranges):
        # within exclude range, skip it
        continue
    # x is within allowed range