Home > Software design >  Python list manipulation, multiple words in an entry
Python list manipulation, multiple words in an entry

Time:09-06

I have a list of different movie genres:

['Action, Adventure, Thriller', 'Comedy, Drama, Romance', 'Adventure, Drama, Romance', 'Crime, Drama', 'Drama, Thriller, War', 'Animation, Adventure, Comedy']

The first list entry 'Action, Adventure, Thriller' consists of the genres of the first movie, the second list entry 'Comedy, Drama, Romance' consists of the genres of the second movie etc...

I want the following output in order to find out how often each genre appears in the list:

['Action', 'Adventure', 'Thriller', 'Comedy', 'Drama', 'Romance', 'Adventure', 'Drama', 'Romance', 'Crime', 'Drama', 'Drama', 'Thriller', 'War', 'Animation', 'Adventure', 'Comedy']

How could I achieve this list where each genre is surrounded by single quotes and separated by comma?

CodePudding user response:

Let's assume your list is called your_list

[word.strip() for words in your_list for word in words.split(',')]

CodePudding user response:

import itertools


a = ['Action, Adventure, Thriller', 'Comedy, Drama, Romance', 'Adventure, Drama, Romance', 'Crime, Drama', 'Drama, Thriller, War', 'Animation, Adventure, Comedy']

b =[x.split(",") for x in a]

c = list(itertools.chain.from_iterable(b))

# or if you can use 
d = [item for sublist in b for item in sublist]

  • Related