janeloulou janeloulou - 9 days ago 6
Python Question

Condition in list - Python

I am working in python and I have this list

for i in range(0, len(state1)):
observations = [{'state_transitions': [{'state': state1[i],
'action': action[i],
'state_': state2[i]},],
'reward': 0},]


I would like to put the for clause inside the observations, something like this (but this is giving me an error):

observations = [
for i in range(0, len(state1)):
{'state_transitions': [{'state': state1[i],
'action': action[i],
'state_':state2[i]},],
'reward': 0},]
print observations;


Can anyone help me with this?

Answer

What you are trying to accomplish (creating a list based on the results from a for loop) is called a list comprehension. Syntax is as follows: my_list = [do_something(item) for item in my_iterable].

Which gives:

observations = [
   { 
      'state_transitions': [
          { 'state': state1[i], 'action': action[i], 'state_':state2[i] },
       ],
        'reward': 0
    } for i in range(0, len(state1))
]
print(observations)
Comments