枚举Python以进行循环
我想将枚举转换为循环。
subsets = [0]*15
subsets[0] = 2
subsets = [index + subsets[subsets[index]] for (index,value) in enumerate(subsets)]
print(subsets)
和类似的结果
subsets = [0]*15
subsets[0] = 2
for index,value in enumerate(subsets):
subsets[index] = index + subsets[subsets[index]]
print(subsets)
,我的结果不同。请帮助我。
I want to convert enumerate to for loop.
subsets = [0]*15
subsets[0] = 2
subsets = [index + subsets[subsets[index]] for (index,value) in enumerate(subsets)]
print(subsets)
and the similar
subsets = [0]*15
subsets[0] = 2
for index,value in enumerate(subsets):
subsets[index] = index + subsets[subsets[index]]
print(subsets)
But I am getting different results. Please help me about this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在第一个版本中,您将根据子集的初始值计算所有内容,在第二个版本中,您将更新到位的元素。
特别是,在第一次迭代中,您将进行
subset [0] = 0 + subset [subsets [0]] = 0 + subsets [2] = 0
。对于第一个代码subset [0]
将为2
,直到执行结束为止。等效的代码将是
In the first version you will compute everything based on the initial values of subsets, in the second version you will update the elements in place.
In particular, on the first iteration you will do
subsets[0] = 0 + subsets[subsets[0]] = 0 + subsets[2] = 0
. While for the first codesubsets[0]
will be2
until the end of the execution.An equivalent code would be
在您的第一种情况下,
subsets的元素
列表不更改,因为您列出了subsets
的新列表(两个名称均相同),并在此列表中添加值。但是在第二种情况下,您在迭代时更新列表值,这就是为什么您获得不同输出的原因。]
执行第二个代码。
(index = 0)
,index + subsets [subsets [index]]
(
subset [index] = 2
)和subsets [index] = 2
(subsets [2] = 0
)结果现在等于0 + 0是0。(index = 1)
,index + subsets [subsets [index]]
(
subset [index] = 0
)和subsets [0] = 0
(因为您将零值更改为第一次迭代中的0)(subsets [2] = 0
)结果现在等于1 + 0。同样,您的
index + subsets的总和[subsets [index]]
始终等于索引值迭代。我希望你能理解
In your first case the elements of the
subsets
list not change because you make a new list ofsubsets
(Both names are same) and add the values in this list.But In your second case you update your list values while iterating through it, THis is why you got different output.]
Execution of your second code.
(index=0)
,index + subsets[subsets[index]]
(
subsets[index]=2
) and aftersubsets[index]=2
(subsets[2]=0
) result is now equal to 0 + 0 which is 0.(index=1)
,index + subsets[subsets[index]]
(
subsets[index]=0
) and aftersubsets[0]=0
(because you change the zero'th value to 0 in first iteration) (subsets[2]=0
) result is now equal to 1 + 0 which is 1.similarly your sum of
index + subsets[subsets[index]]
is always equal to index value of the iteration.I hope you understand
被覆盖并在下一个迭代中使用,等等。
在第二个示例中编写
subset [index] =
时,原始subsets的值
循环,如果您不想要>而不是
subset [value]
。When you write
subsets[index] =
in the second example, the values of the originalsubsets
get overwritten and is used in the next iteration, etc.This is how to write the loop, if you don't want
enumerate
, usefor index in range(len(subsets))
andsubsets[subsets[index]]
instead ofsubsets[value]
.