1

Apologies in advance as I am quite new to this all and I'm not certain on the correct terms for everything.

I have a list of differences between two lists, called Change. I would like to generate a list of percentage changes Percentage by dividing each value in Change by the highest of the respective values in the lists it references (Before and After). If the wrong value is used, a percentage change is showing at -660% in some cases.

Before and After are generated from image files through PIL, but a small section of the output is below.

Before = [135,160,199,]
After = [146,174,176,]
Change = list(After-Before for Before,After in zip(Before,After))
PercentageA = list(Change/After*100 for After,Change in zip(After,Change))
PercentageB = list(Change/Before*100 for Before,Change in zip(Before,Change))
for x in Change:
    if x <0:
        Percentage = PercentageA
    else:
        Percentage = PercentageB
    print(Percentage)

This code generates:

In [1]:
[8.148148148148149, 8.75, -11.557788944723619]
[8.148148148148149, 8.75, -11.557788944723619]
[7.534246575342466, 8.045977011494253, -13.068181818181818]

However, the result should be:

[7.534246575342466, 8.045977011494253, -11.557788944723619]

My main question is; how can I generate a Percentage list from Change divided by the highest of Before and After for each value in the list?

Edit: Reduced and generalised some of the code, and deleted background. Apologies for putting too much background in. Edit2: Apologies for misunderstanding what was asked of me.

malloy_mc
  • 13
  • 3

1 Answers1

0

You are calculating something wrong - this works:

# list must be same lenght for zip() to work
before  = [135, 199]
after   = [146, 176]
change  = [ 11, -23]

print(f"{'before':<10} {'after':<10} {'percent':<10} {'change':<10}")

for b,a,c in zip(before, after, change):
    print (f'{b:<10} {a:<10} {c/max(b,a)*100:<10.6} {c:<10}')

Output:

before     after      percent    change    
135        146        7.53425    11
199        176        -11.5578   -23

Zipping 3 lists creates tuples from each list that this code iterates over. See f.e. The zip() function in Python 3

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • 1
    Thank you very much - this has actually helped me fix it! Sorry for not knowing the correct way to layout things, but this has been very helpful. – malloy_mc Jan 24 '22 at 13:31