Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 list1 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])
like image 966
kenny Avatar asked Nov 11 '16 22:11

kenny


People also ask

How do you split an integer into a single digit in Python?

To split an integer into digits:Use the str() class to convert the integer to a string. Use a list comprehension to iterate over the string. On each iteration, use the int() class to convert each substring to an integer.

How do you combine a list of numbers in one number in Python?

Python3. Approach #2 : Using join() Use the join() method of Python. First convert the list of integer into a list of strings( as join() works with strings only). Then, simply join them using join() method.

How do you separate numbers in a list in Python?

Use the str. split() method to split the string into a list of strings. Use the map() function to convert each string into an integer. Use the list() class to convert the map object to a list.


1 Answers

None of these examples will work if the sum of the first iteration is greater than 10, e.g. 999 -> 27. Interpreting this scenario as 999 -> 27 -> 9, you can use the following function:

>>> def digit_sum(n):
...     while n > 9:
...         n = sum(int(d) for d in str(n))
...     return n
...
>>> [digit_sum(n) for n in [1, 3, 999, 10, 234, 1234132341]]
[1, 3, 9, 1, 9, 6]

This also assumes that all integers are positive.

like image 84
brianpck Avatar answered Oct 22 '22 21:10

brianpck