1

I want to split a value in a list and make it two values.

arr = [10]

The array should turn in to:

arr = [1,0]
User
  • 61
  • 1
  • 13
  • It's different because it is not in a string and I am supposed to solve this wihout a builtin function – User Mar 01 '19 at 01:37

5 Answers5

2

In order to split up an integer in the format like this, you can use str() to make the integer into its parts.

You would need to do this on just the variable not, the list. So

num = arr[0]

and then turn this into a string

string = str(num)

which you can turn into an list with list()

And then you would turn the multiple strings back into numbers with int()

So all together:

>>> arr = [10]
>>> num = arr[0]
>>> string = str(num)
>>> string_arr = list(string)
>>> arr = list(map(int, string_arr))
>>> arr
[1,0]

Or simplified down instead of using intermediate variables.

>>> arr = [10]
>>> arr = list(map(int, str(arr[0])))
>>> arr
[1,0]
The Matt
  • 1,423
  • 1
  • 12
  • 22
1

It can be solved by using map, list, converting to string, list comprehension.

If your list has only one value.

Python 2

arr = [10]
arr = map(int,str(arr[0]))

Python 3

arr = [10]
arr = list(map(int, str(arr[0])))

Both for python 2 and 3

arr = [10]
arr_str=list(str(arr[0]))
arr = [int(x) for x in arr_str]

one Liner

arr = [10]
arr = [int(x) for x in list(str(arr[0]))]
bkawan
  • 1,171
  • 8
  • 14
0

Use list comprehension with two iterations:

>>> [int(x) if x.isdigit() else x for y in arr for x in str(y)]
[1, 0]
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

You can use either a list comprehension:

[int(digit) for digit in str(arr[0])]

Or list(map()):

list(map(int, str(arr[0])))

For the most efficient solution, don't convert to a string; instead, use basic math operations:

import math

[arr[0] // 10 ** n % 10 for n in reversed(range(int(math.log10(arr[0])) + 1))]
iz_
  • 15,923
  • 3
  • 25
  • 40
0

You can use a while loop to keep dividing the given integer by 10 and yielding the remainder until the quotient becomes 0, and then reverse the resulting list to obtain the desired list:

def split_int(i):
    while True:
        i, r = divmod(i, 10)
        yield r
        if not i:
            break

so that list(split_int(arr[0]))[::-1] returns:

[1, 0]
blhsing
  • 91,368
  • 6
  • 71
  • 106