首页 > 解决方案 > 如何有效地将这两个功能合二为一

问题描述

Its basically changing the color of the html row of the table according to 
the value present in c1...c5. The difference between both the function is 
that, in 2nd function I am trying to add the value of "%".

def get_env(lm,mid,c1,c2,c3,c4,c5):
    global tag
    x = []
    for item in lm:
        rnd_off = round(item)
        x.append(rnd_off)
    tag  += '''<tr><th>'''+mid+'''</th>'''
    for i in hey:
        if i <= c1:
            tag += '<td style="background-color:#229954">' + ' ' +  str(i)  + '</td>'
        elif i > c1 and i <= c2:

有人可以告诉我如何通过重复大量代码将这两个函数合并为一种正确的方式。

我可以合并代码但仍然重复一些代码。只需要知道这样做的正确方法。

有人可以告诉我如何将这种正确的方式与重复大量代码合并吗?

标签: pythonpython-3.xpython-2.7

解决方案


这些函数应该返回一个字符串,而不是添加到全局变量中。我认为,颜色是常数,你真的需要给 c1..5 作为参数吗? hey没有定义,我想,这应该是lm

COLORS = {
    c1: '#229954',
    c2: '#ABC878',
    c3: '#F9E79F',
    c4: '#FBD567',
    c5: '#F9C169',
    1e99: '#E67C73',
}

def format_table(lm, mid, row):
    tag  = ['<tr><th>{}</th>'.format(mid)]
    for item in lm:
        for v, color in sorted(COLORS.items()):
            if item < v:
                break
        tag.append(row.format(color, item))
    tag.append('</tr>')
    return ''.join(tag)

def get_env(lm, mid):
    return format_table(lm, mid,
        '<td style="background-color:{}">{:.0f}</td>'
    )

def get_virt_load(lm,mid):
    return format_table(lm, mid,
        '<td style="background-color:{}">{:.0f}%</td>'
    )

推荐阅读