我有一个相当大的(3.9 kB)脚本,旨在根据一些参数,居中等对齐一些文本。
以下是我希望改进的方块:(对于有点代码高手的道歉,但重点不在于函数的作用,而是它们的结构:它们在理论上工作得很好,但我很难让它们更短)
#manage + control the margin in spaces between the body text and right vertical rule
def calcMgn(lnNum): return toEven(bwinner-(len(LnOpn[lnNum])+len(LnCtn[lnNum])),-1)//2
def calcRMgn(lnNum): return (0-(1-(toEven(((bwinner-(len(LnOpn[lnNum])+len(LnCtn[lnNum])))//2),-1))))
def calcLenOf(lnNum): return len(LnMgn[lnNum])+len(LnOpn[lnNum])+len(LnCtn[lnNum])+calcRMgn(lnNum)
def calcRDiff(lnNum): return LnMgnR[lnNum] - (lenOf[lnNum] - bwinner)
def calcRMgnSpa(lnNum): return ((LnMgnRAdjust[lnNum])-adjust)
#there absolutely must be a better way to call a function based on its position in a list than the following:
LnMgn=[calcMgn(0)*spa,calcMgn(1)*spa,calcMgn(2)*spa,calcMgn(3)*spa]
LnMgnR=[calcRMgn(0),calcRMgn(1),calcRMgn(2),calcRMgn(3)]
lenOf=[calcLenOf(0),calcLenOf(1),calcLenOf(2),calcLenOf(3)]
LnMgnRAdjust=[calcRDiff(0),calcRDiff(1),calcRDiff(2),calcRDiff(3)]
LnMgnR_spa=[calcRMgnSpa(0)*spa,calcRMgnSpa(1)*spa,calcRMgnSpa(2)*spa,calcRMgnSpa(3)*spa,]
#take the lengths for a test drive to see if they break any rules
testLen=[LnMgn[0] + LnOpn[0] + spa + LnCtn[0] + LnMgnR_spa[0],\
LnMgn[1] + LnOpn[1] + spa + LnCtn[1] + LnMgnR_spa[1],\
LnMgn[2] + LnOpn[2] + spa + LnCtn[2] + LnMgnR_spa[2],\
LnMgn[3] + LnOpn[3] + spa + LnCtn[3] + LnMgnR_spa[3]] #instead of this, I want something like a for statement or ???
for i in range(0,3):
if len(testLen[i]) > bwinner:
LnMgnR_spa[i] = int((toEven(LnMgnRAdjust[i])-adjust)-(len(testLen[i])-bwinner))*str(spa)
#concatenate strings
addLine=[idt + vl + LnMgn[0] + LnOpn[0] + spa + LnCtn[0] + LnMgnR_spa[0] + vr + nl,\
idt + vl + LnMgn[1] + LnOpn[1] + spa + LnCtn[1] + LnMgnR_spa[1] + vr + nl,\
idt + vl + LnMgn[2] + LnOpn[2] + spa + LnCtn[2] + LnMgnR_spa[2] + vr + nl,\
idt + vl + LnMgn[3] + LnOpn[3] + spa + LnCtn[3] + LnMgnR_spa[3] + vr + nl]
我知道SO的政策是“我们不会为你编写代码”,我绝对不打算要求这样的好处,只是指导:有办法(我用google搜索,并用Google搜索)通过动态迭代调用和自定义基于数组索引的内容,使LnMgn及其类似数组更高效,更小...
答案 0 :(得分:1)
只需使用列表理解。一个例子:
Mod
你可以为所有其他人做同样的事情。
答案 1 :(得分:1)
您还可以创建功能列表:
func_list = [f1, f2, f3, f4]
并打电话给他们,例如:
[func_list[i](i) for i in range(4)]
此示例将返回:
[f1(0), f2(1), f3(2), f4(3)]