Split List into Two Parts Based on Some Delimiter in Each List Element in Python

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

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))

Splitting list into multiple lists - depending on elements index

You could split the strings in a list comprehension and use zip:

list(zip(*[i.split(';') for i in combinedList]))

[('40% Football', '30% Basketball', '20% Baseball', '10% Rugby'),
('40% Football', '30% Basketball', '20% Base-Ball', '10% Le Rugby'),
('40% Fuball', '30% Basketball', '20% Baseball', '10% Rugby'),
('40% Futbol', '30% Baloncesto', '20% Béisbol', '10% Rugby'),
('40% Calcio', '30% Pallacanestro', '', '10% Rugby')]

Split a list in python with an element as the delimiter?

When you write,

new_list = [x.split('a')[-1] for x in l]

you are essentially performing,

result = []
for elem in l:
result.append(elem.split('a')[-1])

That is, you're splitting each string contained in l on the letter 'a', and collecting the last element of each of the strings into the result.

Here's one possible implementation of the mechanic you're looking for:

def extract_parts(my_list, delim):
# Locate the indices of all instances of ``delim`` in ``my_list``
indices = [i for i, x in enumerate(my_list) if x == delim]

# Collect each end-exclusive sublist bounded by each pair indices
sublists = []
for i in range(len(indices)-1):
part = my_list[indices[i]+1:indices[i+1]]
sublists.append(part)
return sublists

Using this function, we have

>>> l = ['a', 'b', 'c', 'c', 'b', 'a', 'b', 'c', 'b', 'a']
>>> extract_parts(l, 'a')
[['b', 'c', 'c', 'b'], ['b', 'c', 'b']]

How to split elements in list?

If you have a small list you can try this:

lst = ['Name0, Location0', 'Phone number0', 'Name1, Location1', 'Phone number1']
s = ", "
joined = s.join(lst)
newList = joined.split(s)
print(newList)

Output:

['Name0', 'Location0', 'Phone number0', 'Name1', 'Location1', 'Phone number1']


Related Topics



Leave a reply



Submit