简体   繁体   English

这个for循环在python中如何工作

[英]how this for loop works in python

I'm new to python. 我是python的新手。 Please anyone help me to understand this statement of python. 请任何人帮助我了解python的此语句。 How it will work ? 它将如何工作?

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

Basically what it do is to create a nested dictionary with all values equal to 0.0 基本上,它要做的是创建一个嵌套字典,所有值都等于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.. 随时发布您尚不清楚的任何内容。

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. 对不起,我的表情不好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM