0

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?

Holloway
  • 6,412
  • 1
  • 26
  • 33
janeloulou
  • 17
  • 5
  • 1
    I think you want list comprehension if I understand what you're saying. The first bit of code would overwrite `observations` with every iteration by the way. – Farhan.K Nov 25 '16 at 13:40
  • You cannot put a for loop inside a list. – Ezio Nov 25 '16 at 13:40

2 Answers2

3

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)
Guillaume
  • 5,497
  • 3
  • 24
  • 42
1

Python does feature a for clause that can go inside list declarations - but it is placed after your expression - so this would work:

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

Besides that, Python's for is designed for higer elvel interations - if what interests you is each item in the sequence, and not the variable i itself, you can use the zip call to yield you one item of each sequence:

observations = [{
    'state_transitions': [{ 'state': st1, 'action': act, 'state_':st2}],
    'reward': 0
    } for st1, act, st2 in zip(state1, action, state2)
]
jsbueno
  • 99,910
  • 10
  • 151
  • 209