python区间访问,Python找到区间的连续相交

本文介绍如何读取包含起始和结束位置的文件,将这些区间合并为连续的整数范围。作者提供了一个Python函数`group`,通过迭代和比较实现区间合并,适用于输入如(1513, 1224)到(1612, 17)这样的数据。
摘要由CSDN通过智能技术生成

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

I would like the output to be:

1 6

9 17

解决方案

Try following:

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

Example:

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

>>> list(group(data))

[(1, 6), (9, 17)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值