Home > Mobile >  if...else..for in list_comprehensions not working
if...else..for in list_comprehensions not working

Time:09-20

I'm trying to make this work but apparently there's some syntax error and I'm struggling to understand what is wrong with it. The part that is not working is the else condition. If I remove it, the first part works as it's supposed to. What I'm trying to do is check if the type of the element (y['type]) is either environmental or shock and based on that return different key:value pairs

mylist=[{'matrice':x['matrice'],'n':x['n'],'id':x['id'],'status':x['status'],
'events':[{'date':y['timestamp'],'type':y['type'],'extradata':{'temp': y['temperature']}} 
for y in db.get_data(x['id']) if y['type']=='environmental' 
else {'date':y['timestamp'],'type':y['type'],'extra':{'Intensity_X': y['x_axis']}}]}
for x in older_stuff]

CodePudding user response:

place your if/else before your first for loop like that:

mylist = [{'matrice': x['matrice'], 'n': x['n'], 'id': x['id'], 'status': x['status'],
           'events': [{'date': y['timestamp'], 'type': y['type'], 'extradata': {'temp': y['temperature']}}
                      if y['type'] == 'environmental'
                      else {'date': y['timestamp'], 'type': y['type'], 'extra': {'Intensity_X': y['x_axis']}}]}
          for y in db.get_data(x['id'])
          for x in older_stuff]

Still. as already pointed out in the comments, in this case it would be much more readable to use multiple statements.

  • Related