Reformation of the unique list to another type of list in Python

Viewed 40

Stackoverflow, hello,

I have very nervous question for me, which I can't solve for several hours now.

Task is:

I have a list:

['Egg', 'Milk', 'Tomato', '_', 'Duck', 'Water', 'Honey', 'Soy', '_', 'Potato', 'Garlic', 'Gouda', '_', 'Beef', 'Sweet', 'Pita', 'Wine', 'Tomato']

And I need to transfrom it into new one, where all the ingridients between '_' will be as a one element:

a= [['Egg', 'Milk', 'Tomato'], ['Duck', 'Water', 'Honey', 'Soy'], ['Potato', 'Garlic', 'Gouda'], ['Beef', 'Sweet', 'Pita', 'Wine', 'Tomato']].

However, the difficult part here, is I may have more "small lists" inside the initial list. For example, after last 'Tomato' it could be a '_' also, and after that - ext few ingridients like ['Bread', 'Milk', 'Egg'], for example.

And the initial list could be look like:

['Egg', 'Milk', 'Tomato', '_', 'Duck', 'Water', 'Honey', 'Soy', '_', 'Potato', 'Garlic', 'Gouda', '_', 'Beef', 'Sweet', 'Pita', 'Wine', 'Tomato', '_', 'Bread', 'Milk', 'Egg']

So I figured out that I MUST NOT make manually 4 different lists and than join them, because there could be 5 or more lists inside the big one, separated by '_'. I must do something else. But all I've got is wrong stuff:

for elem in ingridient_names:
    i=1
    if elem != '_':
        ingridient_names_final[i].append(elem)
print(ingridient_names_final)

Could somebody help, please?

4 Answers

You can use itertools.groupby to group consecutive strings until encountering a '_', then convert those into sublists.

>>> from itertools import groupby
>>> ingridient_names = ['Egg', 'Milk', 'Tomato', '_', 'Duck', 'Water', 'Honey', 'Soy', '_', 'Potato', 'Garlic', 'Gouda', '_', 'Beef', 'Sweet', 'Pita', 'Wine', 'Tomato']
>>> ingridient_names_final = [list(g) for k,g in groupby(ingridient_names, key=lambda i: i!='_') if k]
>>> ingridient_names_final
[['Egg', 'Milk', 'Tomato'],
 ['Duck', 'Water', 'Honey', 'Soy'],
 ['Potato', 'Garlic', 'Gouda'],
 ['Beef', 'Sweet', 'Pita', 'Wine', 'Tomato']]

Another solution would be to convert the list to a string which allow you to use the split method. Probably not very fast but it's a one-liner ;-)

[i.split (',') for i in ','.join (l).split (',_,')]

where l is your initial list

    outer_list = []
    inner_list = []
    for elem in data:
    if elem != '_':
        inner_list.append(elem)
    else:
        outer_list.append(inner_list)
        inner_list = []

This should handle any number of '_' in the main list.

l = ['Egg', 'Milk', 'Tomato', '_', 'Duck', 'Water', 'Honey', 'Soy', '_', 'Potato', 'Garlic', 'Gouda', '_', 'Beef', 'Sweet', 'Pita', 'Wine', 'Tomato']
result = []
tmp = []
for idx, item in enumerate(l):
    if item == "_":
        result.append(tmp)
        tmp = []
    else:
        tmp.append(item)
result.append(tmp)
print(result)
Related