3

Being new to python this has been giving me some trouble

Given a list of integers like

 [2, 0, 0, 0, 0, 12, 0, 8]

how might I extract the indiviual digits of each element to form a new list

 [2,1,2,8] 

I've had the idea of iterating through each element and using the modulo operator but I cant seem to find the correct logic

Any help is very much appreciated

RoadRunner
  • 25,803
  • 6
  • 42
  • 75

3 Answers3

3

The easiest way, I think, is to convert the values to string and extract separate characters and convert them back to integer.

For example:

lst = [2, 0, 0, 0, 0, 12, 0, 8]

digits = []
for value in lst:
    if value != 0:
        digits.extend(map(int, str(value)))

print(digits)

Prints:

[2, 1, 2, 8]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
2

You could first convert all the numbers into lists of strings, convert each string to a integer, then flatten the result with itertools.chain.from_iterable:

>>> from itertools import chain
>>> lst = [2, 0, 0, 0, 0, 12, 0, 8]
>>> list(chain.from_iterable(map(int, str(x)) for x in lst if x != 0))
[2, 1, 2, 8]
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
1

Since 0 is also a digit, Imagine the following case if a number is like 10, 20, 30, 40..... Then it should be like 1, 0, 2, 0, 3, 0... respectively.

SO DO YOU NEED 0 IN YOUR NEW LIST?

If the answer to this question is "NO" Then this and this answers fails. Here's one solution.

myList = [10, 0, 0, 0, 0, 12, 0, 8]

newList = []
for i in myList:
    while i >= 10:
        newList.append(i%10)
        i = i//10
    newList.append(i)

newList = [ x for x in newList if x != 0 ]

This solution also satisfies your modulo logic.