user14800447
user14800447

Reputation: 51

How to Split List Elements in Python

I have a list below. I want to split like:

['Animation','Children's','Comedy','Adventure',"Children's",'Fantasy','Comedy','Romance','Comedy','Drama']

clist = ["Animation|Children's|Comedy",

"Adventure|Children's|Fantasy",

'Comedy|Romance',

'Comedy|Drama']

 

for i,x in enumerate(clist):

    if '|' in x:

        clist[i] = x[:x.index('|')]

it return this:

['Animation', 'Adventure', 'Comedy', 'Comedy']

Upvotes: 0

Views: 72

Answers (3)

Turtlean
Turtlean

Reputation: 579

You could take advantage of nested comprehension lists to achieve the goal:

clist = ["Animation|Children's|Comedy", "Adventure|Children's|Fantasy", 'Comedy|Romance', 'Comedy|Drama']

l = [ pipe_elem for child in clist for pipe_elem in child.split('|') ]

print(l)
# Output: ['Animation', "Children's", 'Comedy', 'Adventure', "Children's", 'Fantasy', 'Comedy', 'Romance', 'Comedy', 'Drama']

Upvotes: 2

ouroboring
ouroboring

Reputation: 681

There are a number of ways of doing this in Python, but one way would be using a list comprehension, like this:

clist = [genre for glist in clist for genre in glist.split('|')]

This will set clist to ['Animation','Children's','Comedy','Adventure',"Children's",'Fantasy','Comedy','Romance','Comedy','Drama'].

To explain what this is actually doing, it loops through clist, assigning each element to the glist variable, then splits glist at every | character, and then adds an element for each element in the resulting list.

Upvotes: 2

Samwise
Samwise

Reputation: 71434

I recommend using split in a comprehension if you want to produce the same result:

>>> [c.split("|")[0] for c in clist]
['Animation', 'Adventure', 'Comedy', 'Comedy']

If you want all of the individual list elements instead of just the first one, flattened into a single list, that'd be just one more nested comprehension:

>>> [g for c in clist for g in c.split("|")]
['Animation', "Children's", 'Comedy', 'Adventure', "Children's", 'Fantasy', 'Comedy', 'Romance', 'Comedy', 'Drama']

Upvotes: 5

Related Questions