Home > Back-end >  How to extract elements from a list when the list is made of string and list of differents size?
How to extract elements from a list when the list is made of string and list of differents size?

Time:07-08

I have a list made of lists and strings, and I want to extract each element from the list. And if the extracted element is a list, extract the elements from the list.

This is just to manipulate the lists a bit so I don't have anything planned with these items once done, so after that puting them in another list is enought.

for example, i have this list :

meal = [
    'salad',
    ['coquillette', 'ratatouille', 'steak'],
    'cheese', ['ice cream', 'tart', 'fruit']
]

and I want :

dishes = [
    'salad',
    'coquillette',
    'ratatouille',
    'steak',
    'cheese',
    'ice cream',
    'tart',
    'fruit'
]

for the moment I have done this :

meal = ['salad', ['coquillette', 'ratatouille', 'steak'], 'cheese', ['ice cream', 'tart', 'fruit']]
dishes = []

for dish in meal:
    for item in dish:
        if isinstance(dish, list):
            dishes.append(item)
            #print(item)
    else:
        dishes.append(dish)
        #print(dish)

print(dishes)

but I get :

[
    'salad',
    'coquillette',
    'ratatouille',
    'steak',
    **['coquillette', 'ratatouille', 'steak']**,
    'cheese',
    'ice cream',
    'tart',
    'fruit',
    **['ice cream', 'tart', 'fruit']**
]

any advices ?

CodePudding user response:

You can do something like this:

meal = ['salad', ['coquillette', 'ratatouille', 'steak'], 'cheese', ['ice cream', 'tart', 'fruit']]
out = []
for m in meal:
  out  = [m] if not isinstance(m, list) else m
print(out)

['salad', 'coquillette', 'ratatouille', 'steak', 'cheese', 'ice cream', 'tart', 'fruit']

CodePudding user response:

You were very close:

...
for dish in meal:
    if isinstance(dish, list):
        for item in dish:
            dishes.append(item)
...

CodePudding user response:

meal = ['salad', ['coquillette', 'ratatouille', 'steak'], 'cheese', ['ice cream', 'tart', 'fruit']]
dishes = []

for dish in meal:
    if isinstance(dish, list):
        dishes.extend(dish)
    else:
        dishes.append(dish)

print(dishes)

CodePudding user response:

My weird one liner :D [ s for tmpL in [[*e] for e in L] for s in tmpL]

Recursive general solution

def flat_rec(l: list):
   for e in l:
      if isinstance(e,str):
         yield e
      elif isinstance(e,list):
         yield flat_rec(e)
      else:
         raise ValueError("Oh no!")

CodePudding user response:

for i in my_list:
    if type(i) == str:
        other_list.append(i)
    elif type(i) == list:
        for x in i:
            other_list.append(x)

This should work

  • Related