Home > Net >  How to calculate each number of a list in python like arr = [22, 43, 54, 67] i want to get 2 2 = 4 ,
How to calculate each number of a list in python like arr = [22, 43, 54, 67] i want to get 2 2 = 4 ,

Time:09-30

How to calculate each number of a list in python like arr = [22, 43, 54, 67] i want to get 2 2 = 4 , 4 3 = 7, 5 4 = 9 , 6 7 = 13 that will be n number of times not by index.

input [22, 43, 54, 67] output [4, 7, 9, 13]

CodePudding user response:

arr = [22, 43, 54, 67] 
x = 0
output = []
for i in arr :
    for j in str(i):
        x  = int(j)
    output.append(x)
    x = 0

CodePudding user response:

arr = [22, 43, 54, 67] 
result = []

for num in arr:
    s = 0
    for digit in str(num):
        s  = int(digit)
    result.append(s)

print(result)

Or if you want a one liner:

arr = [22, 43, 54, 67] 

result = list(map(lambda x: sum([int(i) for i in str(x)]), arr))

print(result)
  • Related