找到一系列数字之间的数字

时间:2013-08-12 22:38:52

标签: python unix sed awk

我的文件1的范围是这样的

  

10 20

     

50 60

     

70 100

     

150 170

     

...

     

...

file2的

  

15

     

55

     

80

     

160

     

...

     

...

我想读取file1中的范围并查看file2并获取它们之间的值

最终输出:

  

15是介于10和20之间的值

     

55是介于50和60之间的值

     

...

     

...

3 个答案:

答案 0 :(得分:1)

如果您想对结果执行某些操作而不是打印出来,您可以创建一个字典,将范围(从file1)映射到这些范围内的数字(来自file2。)

ranges = []
with open('file1') as f:
    for line in f:
        ranges.append(line.strip().split(' '))
ranges = [tuple(int(_) for _ in r) for r in ranges]
in_range = {range_: set() for range_ in ranges}
with open('file2') as f:
    for line in f:
        num = int(line.strip())
        for range_ in ranges:
            if range_[0] < num < range_[1] # Between low and high
                in_range.add(num)
# print in_range

答案 1 :(得分:0)

在Python中,这是如何...

打开文件:

with open('thefile.txt') as f:

迭代文件的行:

for line in f:

在一行末尾丢掉额外的空格:

line = line.rstrip()

在第一个空格块周围将每一行拆分为两行:

left, right = line.split(None, 1)

将字符串转换为数字:

low = int(low)

获取两个其他数字之间的数字:

mid = (low + high) // 2

或者,检查一个数字是否在两个其他数字之间:

if low <= mid <= high:

打印格式化结果:

print('{} is the value between {} and {}'.format(mid, low, high))

当然你也想要一些错误处理,你必须将整个事情放在一起,但这应该足以自己完成它。

答案 2 :(得分:-1)

这应该可以解决问题:

with open('file1.txt') as file1, open('file2.txt') as file2:
    ranges = [line.split(' ') for line in file1 if line.rstrip()]
    values = filter(lambda line: bool(line.rstrip()), file2.readlines())
for value, _range in zip(values, ranges):
    print("{} is {}the value between {} and {}".format(value, "not " if int(_range[0]) <= float(value) <= float(_range[1]) else "", _range[0], _range[1])