star123
star123

Reputation: 333

how this for loop works in python

I'm new to python. Please anyone help me to understand this statement of python. How it will work ?

  {x: {y: 0. for y in myClass.features} for x in myClass.items}

Upvotes: 1

Views: 87

Answers (2)

rint
rint

Reputation: 457

Just give it a try.

{x: {y: 0. for y in [1,2,3]} for x in ['a','b','c']}

=

{'a': {1: 0.0, 2: 0.0, 3: 0.0}, 'b': {1: 0.0, 2: 0.0, 3: 0.0}, 'c': {1: 0.0, 2: 0.0, 3: 0.0}}

Then ones can have some feeling about it from the output.


To be easier, you can decompose it:

{y: 0. for y in [1,2,3]}

=

{1: 0.0, 2: 0.0, 3: 0.0}

after substitution, we have

{x: {1: 0.0, 2: 0.0, 3: 0.0} for x in ['a','b','c']}

final answer =

{'a': {1: 0.0, 2: 0.0, 3: 0.0}, 'b': {1: 0.0, 2: 0.0, 3: 0.0}, 'c': {1: 0.0, 2: 0.0, 3: 0.0}}

Now you only need to replace

[1,2,3] and ['a','b','c']

to

myClass.features and myClass.items

Both are implicitly declared by defining them.


Sorry for my poor expression.

Upvotes: 0

Marcus.Aurelianus
Marcus.Aurelianus

Reputation: 1518

Basically what it do is to create a nested dictionary with all values equal to 0.0

class myClassrino:
    def __init__(self):
        self.features=[1,2,3,4,5]
        self.items=[3,4,5,6]

myClass=myClassrino()
output={x: {y: 0. for y in myClass.features} for x in myClass.items}
print(output)

Output is:

{3: {1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0}, 4: {1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0}, 5: {1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0}, 6: {1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0}}

Feel free to post anything you are still unclear..

Upvotes: 2

Related Questions