Python找到区间的连续相交

Python找到区间的连续相交

本文介绍了Python找到区间的连续相交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我厌倦了多种方法,但未能完成这项工作.它们全部仅使用2个列表或列表范围.最有前途的一个是:

I tired multiple approaches, but failed to do this one job. All of them use only 2 lists or range of lists.The one most promising was:

infile = open('file','r')

for line in infile:
    line = line.split()
    f = range(int(line[0]),int(line[1]))

results_union = set().union(*f)
print results_union

我有一个文件的开头,结尾位置是这样的:(已排序)

I have a file with start,end positions like this: (sorted)

1 5
1 3
1 2
2 4
3 6
9 11
9 16
12 17

我希望输出为:

1 6
9 17

推荐答案

尝试以下操作:

def group(data):
    data = sorted(data)
    it = iter(data)
    a, b = next(it)
    for c, d in it:
        if b >= c:  # Use `if b > c` if you want (1,2), (2,3) not to be
                    # treated as intersection.
            b = max(b, d)
        else:
            yield a, b
            a, b = c, d
    yield a, b


with open('file') as f:
    data = [map(int, line.split()) for line in f]

for a, b in group(data):
    print a, b

示例:

>>> data = (9,16), (1,5), (1,3), (1,2), (3,6), (9,11), (12,17), (2,4),
>>> list(group(data))
[(1, 6), (9, 17)]

这篇关于Python找到区间的连续相交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-09 18:21