bornTalented
bornTalented

Reputation: 625

Split list into two parts based on some delimiter in each list element in python

I have a python list

my_list = ['owner/NN', 'is/VBZ', 'pleasant/JJ', 'and/CC', 'entertaining/JJ', './.']

I want to split it into two parts (based on delimeter '/' presented in each list element), so that I can get two seperate list

my_list_1 = ['owner', 'is', 'pleasant', 'and', 'entertaining', '.']
my_list_2 = ['NN', 'VBZ', 'JJ', 'CC', 'JJ', '.']

Upvotes: 2

Views: 1469

Answers (4)

Austin
Austin

Reputation: 26039

Use split to split on delimiter:

my_list = ['owner/NN', 'is/VBZ', 'pleasant/JJ', 'and/CC', 'entertaining/JJ', './.']

lst1, lst2 = [], []
for x in my_list:
    part1, part2 = x.split('/')
    lst1.append(part1)
    lst2.append(part2)

Or using list comprehensions:

lst1, lst2 = [x.split('/')[0] for x in my_list], [x.split('/')[1] for x in my_list]

Upvotes: 2

Gaurav Goswami
Gaurav Goswami

Reputation: 32

There you go:

my_list = ['owner/NN', 'is/VBZ', 'pleasant/JJ', 'and/CC', 'entertaining/JJ', './.']
my_list_1 = []
my_list_2 = []
delim = '/'
for item in my_list:
    parts = item.split(delim)
    my_list_1.append(parts[0])
    my_list_2.append(parts[1])

Upvotes: 0

Maarten Fabré
Maarten Fabré

Reputation: 7058

split_items = (i.split('/') for i in my_list)
my_list1, my_list2 = zip(*split_items)

This creates 2 tuples. If you really need lists, you can convert them by

my_list1, my_list2 = map(list, (my_list1, my_list2))

Upvotes: 7

Federico Ponzi
Federico Ponzi

Reputation: 2785

You can use a simple for loop and split:

my_list = ['owner/NN', 'is/VBZ', 'pleasant/JJ', 'and/CC', 'entertaining/JJ', './.']

my_list1 = []
my_list2 = []
for el in my_list:
     my_list1.append(el.split("/")[0])
     my_list2.append(el.split("/")[1])


>>> my_list1
['owner', 'is', 'pleasant', 'and', 'entertaining', '.']
>>> my_list2
['NN', 'VBZ', 'JJ', 'CC', 'JJ', '.']

Upvotes: 1

Related Questions