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])
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With