0

I've got a bunch of numbers in a string. I want to split them into individual digits so I can do more with them later.

number = [6, 18, 6, 4, 12, 18, 0, 18]

I want to split these like so.... ex: 6, 1, 8, 6, 4, 1, 2, 1, 8, 0, 1, 8

I've tried split(), I've tried list(str(number)), I've tried converting these to strings and integers and I have tried searching stackoverflow.

In other searches I keep seeing a list comprehension example like this, which I don't understand and don't get the desired result after trying: [int(i) for i in str(number)]

help??

3 Answers 3

2

First you have to consider every element of the list as a string, and then cast back every character to an integer.

def customSplit(l):
        result = []
        for element in l:
                for char in str(element):
                        result.append(int(char))
        return result

print(customSplit([6, 18, 6, 4, 12, 18, 0, 18]))
# prints [6, 1, 8, 6, 4, 1, 2, 1, 8, 0, 1, 8]
Sign up to request clarification or add additional context in comments.

Comments

2

How about a list comprehension:

[ digit for x in number for digit in str(x) ]

which produces a list of strings:

['6', '1', '8', '6', '4', '1', '2', '1', '8', '0', '1', '8']

or

[ int(digit) for x in number for digit in str(x) ]

if you'd prefer a list of single-digit integers:

[6, 1, 8, 6, 4, 1, 2, 1, 8, 0, 1, 8]

Comments

0

You can use itertools.chain like so:

>>> list(map(int, chain.from_iterable(map(str, numbers))))
[6, 1, 8, 6, 4, 1, 2, 1, 8, 0, 1, 8]

I posted this mainly so I could compare it to a Coconut equivalent:

>>> numbers |> map$(str) |> chain.from_iterable |> map$(int) |> list

while looks nicer. If you like Unicode characters, you can replace |> with :

>>> numbers ↦ map$(str) ↦ chain.from_iterable ↦ map$(int) ↦ list

In standard Python, a list comprehension is probably more readable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.