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个其他打印语句,例如那些稳定地使代码很难使用的打印语句?
答案 0 :(得分:2)
将模板写为“常量”,然后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)
答案 1 :(得分:1)
您可以创建包含所有标签和值的元组列表,并执行如下循环:
if report:
values = [
("Active parts:", pact),
("Discontinued parts:", pdisc),
# etc...
]
for label, value in values:
print ("\t{}\t{}".format(label, len(value)))
答案 2 :(得分:0)
定义一个方法,以便您可以发送一个列表并使用'\ n'
加入列表答案 3 :(得分:0)
对代码进行重新分解,以便将各个变量存储在字典中,例如
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