为什么`prev = poss [0]`和`prev = 0`表现不同?(Why do `prev = poss[0]` and `prev = 0` behave differently?)

编程入门 行业动态 更新时间:2024-10-21 15:57:57
为什么`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 poss

The 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 = 0

it 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.

更多推荐

本文发布于:2023-08-06 17:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1453824.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:poss   prev   differently   behave

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!