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)]