0

I have a lists A=[1, 1, 1, 1] and B=[2, 3, 4, 5], and I want to define C=[50%, 33%, 25%, 20%] (i.e. I'm dividing each element of A by the corresponding element of B and then multiplying each by 100 to get the percentage).

When trying to find out how to do the division I came across: Dividing elements of one list by elements of another but this case is much more complex than what I need so I got really confused.

Thanks in advance!

anky
  • 74,114
  • 11
  • 41
  • 70
user356
  • 303
  • 2
  • 10

5 Answers5

2
C = [a/b*100 for a, b in zip(A,B)]
politinsa
  • 3,480
  • 1
  • 11
  • 36
1
c = [a / b * 100 for (a, b) in zip(A, B)]
Luke Storry
  • 6,032
  • 1
  • 9
  • 22
1

You may abstract away your operations with own classes and a dunder function:

class AdvancedList(list):

    def __truediv__(self, other):
        result = [x / y for x, y in zip(self, other)]
        return result


A = AdvancedList([1, 1, 1, 1])
B = AdvancedList([2, 3, 4, 5])
print(A / B)

Which yields

[0.5, 0.3333333333333333, 0.25, 0.2]
Jan
  • 42,290
  • 8
  • 54
  • 79
0

Try this:

for i in range(len(A)):
    A[i] = str(A[i]/B[i] * 100) + "%"
Krishnan Shankar
  • 780
  • 9
  • 29
0

convert it to string....xx%

result = ["%.0f%%"%(a*100 / b) for a, b in zip(A, B)]
# ['50%', '33%', '25%', '20%']

Attention:if you don't want to round this number,

result = ["%.d%%"%(a*100 / b) for a, b in zip(A, B)]
Kevin Mayo
  • 1,089
  • 6
  • 19