kenny kenny - 11 months ago 43
Python Question

converting two digit integer into single digit inside a python list?

list1 = [6,10,4,8,2,12,10]

I want to convert all the integers in
which are greater than or equal to 10 into a single integer. For example,
10: 1+0=1
12: 1+2=3
. The output list should be:

list1 = [6,1,4,8,2,3,1]

Can anyone please help me with the logic? The logic I tried so far which is not working:

for itr in list1:
if ( itr >= 10):
itr1 = str(itr)
itr2 = eval(itr[0]+itr[1])

Answer Source

For small numbers you can sum up the individual digits by iterating over the str(num)

[sum(int(c) for c in str(num)) for num in list1]

For larger numbers where the sum of the digits can be >9, you can use divmod to avoid converting to str:

def reduce_num(n):
    while n > 9:
        n = sum(divmod(n, 10))
    return n

[reduce_num(num) for num in list1]

Or none iteratively (slight fix to @suspicious_dog):

[n-9*int((n-1)/9) for n in list1]    # change to /9.0 for Py2