Python找到区间的连续相交

编程入门 行业动态 更新时间:2024-10-23 13:35:20
本文介绍了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找到区间的连续相交

本文发布于:2023-11-29 08:38:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645894.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区间   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!