Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a list and into a tuple

If i have a list

lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']  

and I want to split into new list without 'k', and turn it into a tuple. So I get

(['a'],['b', 'c'], ['d', 'e', 'g'])

I am thinking about first splitting them into different list by using a for loop.

new_lst = []
for element in lst:
    if element != 'k':
        new_ist.append(element)

This does remove all the 'k' but they are all together. I do not know how to split them into different list. To turn a list into a tuple I would need to make a list inside a list

a = [['a'],['b', 'c'], ['d', 'e', 'g']]
tuple(a) == (['a'], ['b', 'c'], ['d', 'e', 'g'])
True

So the question would be how to split the list into a list with sublist.

like image 300
Cup Avatar asked Dec 18 '22 19:12

Cup


1 Answers

You are close. You can append to another list called sublist and if you find a k append sublist to new_list:

lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']

new_lst = []
sublist = []
for element in lst:
    if element != 'k':
        sublist.append(element)
    else:
        new_lst.append(sublist)
        sublist = []

if sublist: # add the last sublist
    new_lst.append(sublist)

result = tuple(new_lst) 
print(result)
# (['a'], ['b', 'c'], ['d', 'e', 'g'])

If you're feeling adventurous, you can also use groupby. The idea is to group elements as "k" or "non-k" and use groupby on that property:

from itertools import groupby

lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']
result = tuple(list(gp) for is_k, gp in groupby(lst, "k".__eq__) if not is_k)

print(result)
# (['a'], ['b', 'c'], ['d', 'e', 'g'])

Thanks @YakymPirozhenko for the simpler generator expression

like image 91
slider Avatar answered Dec 20 '22 07:12

slider