Mutation and Iteration
Posted 爱学英语的程序媛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mutation and Iteration相关的知识,希望对你有一定的参考价值。
- avoid mutating a list as you are iterating over it
代码:
def remove_dups(L1,L2):
for e in L1:
if e in L2:
L1.remove(e)
L1=[1,2,4,5]
L2=[2,3,1,6]
remove_dups(L1,L2)
L1
》[2, 4, 5]
L2
》[2, 3, 1, 6]
L1 is [2,4,5], not [4,5] why?
Python uses an internal counter to keep track of index it is in the loop
mutating changes the list length but Python doesn‘t update the counter
loop never sees element 2
所以上述代码是有问题的,可改为:
def remove_dups_new(L1,L2):
L1_copy = L1[:]
for e in L1_copy:
if e in L2:
L1.remove(e)
以上是关于Mutation and Iteration的主要内容,如果未能解决你的问题,请参考以下文章
[Chapter 2] Value Iteration and Policy Iteration
人工智能之计算最佳策略(Policy Iteration and Value Iteration)
增强学习Reinforcement Learning经典算法梳理1:policy and value iteration
增强学习Reinforcement Learning经典算法梳理1:policy and value iteration
[Vue + TS] Use Dependency Injection in Vue Using @Inject and @Provide Decorators with TypeScript(代码片
[原创][Synth 8-2543] port connections cannot be mixed ordered and named ["*_Top.v":1151](代码片