我正在学习python(2.7)并尝试打印这两个文件范围,如果它们重叠的话。
在文件input1.txt中说,我有 -
p1234: 4-5, 7-12, 15-19
p5678: 7-59, 78-345
p4356: 3-4, 6-10
在文件input2.txt -
中p1234: 1-3, 6-13, 16-20, 22-25
p4356: 9-10
从这两个输入文件中,我想只保留两个输入文件中每个id(每个文件中最左边一列)相互重叠的范围,并丢弃其他范围。
也就是说,两个输出文件如下:
output1.txt -
p1234: 7-12, 15-19
p4356: 6-10
output2.txt -
p1234: 6-13, 16-20
p4356: 9-10
我了解到只打印那些重叠的范围,我可以使用:
x = range(1,10)
y = range(8,20)
intersection = [i for i in x if i in y]
try:
print x
print y
except NameError:
print intersection
这给出了:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
我可以从这里得到两个范围(尽管最后一个数字重叠未显示),但我不知道如何在匹配它们的ID之后仅打印两个输入文件重叠的区域(在两个输出文件中)格式)。请帮忙。
感谢您的考虑。
答案 0 :(得分:0)
正如我在评论中所建议的那样,并进一步使用你已经开始的东西。以此函数为例:
def intersect_or_not(range_, list_of_ranges):
for range2_ in list_of_ranges:
intersections = [i for i in range_ if i in range2_]
if intersections:
return True # return also breaks (if one range intersected you have a match!)
return False
x = range(1,10)
y = [range(8,20),range(9,20)]
print(intersect_or_not(x,y))
#True
我想你知道该怎么做! :)
好的,这有点过于复杂,但无论如何我都会发布它。 假设您将文件读入元组(startpos,endpos),您可以找到如下值:
def intersect_or_not(range_, list_of_ranges):
for range2_ in list_of_ranges:
intersections = [i for i in range_ if i in range2_]
if intersections:
return True
return False
list1 = [(4,5), (7,12), (15,19)]
list2 = [(1,3), (6,13), (16,20), (22,25)]
#output 1
[i for i in list1 if intersect_or_not(range(*i),[range(*ii) for ii in list2])]
# [(7, 12), (15, 19)]
#output 2
[i for i in list2 if intersect_or_not(range(*i),[range(*ii) for ii in list1])]
# [(6, 13), (16, 20)]