首页 养生问答 疾病百科 养生资讯 女性养生 男性养生

python怎样比较两列的大小(选出满足条件的记录),其中一列有大于小于号...

发布网友

我来回答

1个回答

热心网友

import re

def get_test_func(op):
    if op == '<':
        return lambda x, y: x < y
    elif op == '>':
        return lambda x, y: x > y
    elif op == '<=':
        return lambda x, y: x <=y
    elif op == '>=':
        return lambda x, y: x >= y
    raise ValueError('Unknown operator %s' % op)

with open('input.txt', 'r') as fin:
    next(fin)
    for row in fin:
        cols = row.split()
        x = float(cols[1])
        m = re.match(r'([><]=?)(\d+(?:\.\d+))', cols[2])
        if m:
            op, y = m.group(1), float(m.group(2))
            test = get_test_func(op)
            if test(x, y):
                print('Row %s: Value %s satisfies constraint: %s' % (cols[0], cols[1], cols[2]))
        else:
            print('Row %s: Incorrect format: %s' % (name, cols[2]))

输入文件:

col1 col2 col3

row1 7 <=0.5

row2 7 >0.5

输出结果:

Row row2: Value 7 satisfies constraint: >0.5

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com