How to split a list and into a tuple

  • A+
Category:Languages

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.

 


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'] transformed = [(0, x) if x == 'k' else (1, x) for x in lst]  result = tuple([y[1] for y in g] for not_k, g in groupby(transformed, key=lambda x: x[0]) if not_k) print(result) # (['a'], ['b', 'c'], ['d', 'e', 'g']) 

Edit: Or even simpler as @YakymPirozhenko suggests:

tuple(list(gp) for is_k, gp in groupby(lst, "k".__eq__) if not is_k) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: