简化以下代码的最佳方法是什么?

2024-09-29 17:12:35 发布

您现在位置:Python中文网/ 问答频道 /正文

if report == True:  
    print ("\tActive parts:\t%s")%(len(pact)) # TOTAL P Part and Active
    print ("\tDiscontinued parts:\t%s")%(len(pdisc)) # TOTAL P Part and Discontinued
    print ("\tSlow-moving parts:\t%s")%(len(pslow)) # TOTAL P Part and Slow-moving
    print ("\tObsolete parts:\t%s")%(len(pobs)) # P TOTAL Part and Obsolete

我怎样才能最好地简化上述内容?我还有大约80条其他的打印语句,比如那些使代码很难使用的语句?你知道吗


Tags: andreporttruelenif语句activetotal
3条回答

把模板写成“常量”,然后print( template % dictionary_of_values)

澄清:

template = """\tActive parts:\t%(pactlen)d
\tDiscontinued parts:\t%(pdisclen)d
..."""
...
values = {'pactlen':len(pact), 'pdisclen':len(pdics) }
print(template % values)

重新考虑代码的因素,以便将各个变量存储在字典中,例如

data['pact']  = ...
data['pdisc'] = ...

甚至作为类的属性

class Data:
    pact = ...
    pdisc = ...

然后创建一个单独的字符串列表来描述每个属性,例如:

longnames = {"pact": "Active parts", "pdisc": "Discontinued parts", ... }

然后你可以这样打印它们:

if report:
    for key, name in values:
        print "\t%s\t%d" % (name, len(data[key])) # if using a dict
        print "\t%s\t%d" % (name, len(getattr(data, key))) # if using a class

您可以创建一个包含所有标签和值的元组列表,并执行如下循环:

if report:
    values = [
        ("Active parts:", pact),
        ("Discontinued parts:", pdisc),
        # etc...
    ]
    for label, value in values:
        print ("\t{}\t{}".format(label, len(value)))

相关问题 更多 >

    热门问题