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?

2
  • 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. Commented Nov 25, 2016 at 13:40
  • You cannot put a for loop inside a list. Commented Nov 25, 2016 at 13:40

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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)
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.