为什么`prev = poss [0]`和`prev = 0`表现不同?(Why do `prev = poss[0]` and `prev = 0` behave differently?)
我对此代码有疑问:
poss = [6,9,20] for n in range(6,66): if(n%6) == 0 or (n%9) == 0 or (n%20) == 0: poss.append(n) poss.sort() count = 0 prev = poss[0] for p in poss: print p if prev == p: del poss[count] count += 1 prev = p print poss第二个for循环旨在消除poss列表中的重复项,此代码正常工作。 但是,如果我更改了该行:
prev = poss[0]至
prev = 0它不会正确删除它们。 对于我的生活,我无法弄清楚为什么。
I have a question about this code:
poss = [6,9,20] for n in range(6,66): if(n%6) == 0 or (n%9) == 0 or (n%20) == 0: poss.append(n) poss.sort() count = 0 prev = poss[0] for p in poss: print p if prev == p: del poss[count] count += 1 prev = p print possThe 2nd for loop is intended to get rid of duplicates in the poss list and this code works correctly. However, if I change the line:
prev = poss[0]to
prev = 0it won't correctly delete them. For the life of me, I can't figure out why.
最满意答案
为什么不直接将一个集合删除重复项? 例如
poss = set(poss)要回答您的原始问题, prev = poss[0]与prev = 0因为poss[0]不为0。
Why not just make poss into a set to remove the duplicates? E.g.
poss = set(poss)To answer your original question, prev = poss[0] is not the same as prev = 0 because poss[0] is not 0.
更多推荐
发布评论