문제

The following python code works but the maintainability is quite poor.

However I'm failing to see a better way to implement the code to improve maintainability.

extraval = ""
if aline[0:1] == "-":
    extraval = '"expanded":true, '
    aline = aline[1:] 
if aline[0:1] == "+":
    extraval = '"expanded":false, '
    aline = aline[1:] 

When I need to work in extra parameters, the code keeps doubling.

도움이 되었습니까?

해결책

You can use a dict to map the target keys to their associated values. It would then be trivial to check if a specific key exists and return the associated values of matching keys.

For example:

m = { 
  "-" : '"expanded":true, ',
  "+" : '"expanded":false, ',
}

if aline[0] in m:
  extraval = m[aline[0]]
  aline = aline[1:]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top