Turkey
Turkey

Reputation: 45

How to split elements in a list Python

say i've got a list where each element contains more than 1 character like such:

ls = [" *X* ", " *** ", " W** "]

and I want to separate the multiple charactered elements into individual elements like this:

ls = [" * ", "X", " * ", " * ", " * ", " * ", "W", " * ", " * "]

How would I do that?

Upvotes: 0

Views: 1660

Answers (7)

Jason Groulx
Jason Groulx

Reputation: 410

You could use list comprehensions like this

ls = [" *X* ", " *** ", " W** "]
l = [x.strip() for sublist in ls for x in sublist if x.strip()]
print(l)

Output

['*', 'X', '*', '*', '*', '*', 'W', '*', '*']

Upvotes: 0

allexiusw
allexiusw

Reputation: 1743

Hello this is my solution, as I realized in the comment you wanted to skip spaces and when the character is * you have to put it between spaces, here is my solution:

ls = [" *X* ", " *** ", " W** "]
newls =[]
for ele in ls:
    for char in ele:
        if char==" ":
            continue;
        if char=="*":
            char=" "+char+" "
        newls.append(char)
print(newls)

And this is the output: [' * ', 'X', ' * ', ' * ', ' * ', ' * ', 'W', ' * ', ' * ']

I hope this can help you.

Upvotes: 0

RoadRunner
RoadRunner

Reputation: 26335

You could add spaces around * items, and filter out empty spaces with isspace():

>>> ls = [" *X* ", " *** ", " W** "]
>>> [f" {c} " if c == "*" else c for s in ls for c in s if not c.isspace()]
[' * ', 'X', ' * ', ' * ', ' * ', ' * ', 'W', ' * ', ' * ']

If we don't care about spaces around *, then we can simplify the above:

>>> [c for s in ls for c in s if not c.isspace()]
['*', 'X', '*', '*', '*', '*', 'W', '*', '*']

Also note the [c for s in ls for c in s] simply flattens the list.

Upvotes: 0

Transhuman
Transhuman

Reputation: 3547

simple join + split will work

print (''.join(ls).split())
#['*', 'X', '*', '*', '*', '*', 'W', '*', '*']

if you are looking to have spaces in your elements

print ([i if i!='*' else f' {i} ' for i in ''.join(ls).replace(' ','')])
#[' * ', 'X', ' * ', ' * ', ' * ', ' * ', 'W', ' * ', ' * ']

Upvotes: 0

tzaman
tzaman

Reputation: 47850

A nested list comprehension is a quick and easy way to flatten:

ls = ["*X*", "***", "W**"]
flattened = [char for entry in ls for char in entry]
# Produces ['*', 'X', '*', '*', '*', '*', 'W', '*', '*']

Upvotes: 1

Saran
Saran

Reputation: 1844

ls = [" *X* ", " *** ", " W** "]

def split(word): 
    return [char for char in word.strip() ] 

splitted_list = []
for word in ls:
        splitted_list.extend(split(word))

print(splitted_list)

['*', 'X', '*', '*', '*', '*', 'W', '*', '*']

Upvotes: 0

Ketan Krishna Patil
Ketan Krishna Patil

Reputation: 81

Try this,

ls = ["*X*", "***", "W**"]
output = []
for i in ls:
    output.extend(list(i.strip()))

print(output)

Upvotes: 1

Related Questions