有人可以尝试向我解释这段代码是如何工作的吗?(编程与莫什的)



所以基本上,我真的不明白这个简单的代码有什么意义。其目的是识别列表中的重复项并将其删除。代码为:

number = [1,2,3,4,5,5,6,6,7,8,9]
newnum = []
for num in number:
if num not in newnum:
newnum.append(num)
print(newnum)

具体来说,如果num不在newnum中,为什么它需要与空列表而不是原始列表进行比较?这是如何工作的,它如何知道数字列表中的数字不在newnum列表中?当我第一次想到解决这个问题的方法时,它几乎是一样的,但我会放一个!=但(希望这也是可能的(我放弃了。如果有人愿意尝试解释这个简单的问题,非常感谢!

让我们稍微更改一下原始序列(使其更有趣(,并添加一个print(),这是最古老的调试工具,可以查看newnum在循环过程中的演变:

number = [1,2,3,4,6,5,5,6,6,7,8,9]
newnum = []
for i, num in enumerate(number):
print(f"{i=}, {num=}, {newnum=}")
if num not in newnum:
newnum.append(num)
print(newnum)

输出是(突出显示我的(

i=0, num=1, newnum=[]
i=1, num=2, newnum=[1]
i=2, num=3, newnum=[1, 2]
i=3, num=4, newnum=[1, 2, 3]
i=4, num=6, newnum=[1, 2, 3, 4]
i=5, num=5, newnum=[1, 2, 3, 4, 6]  # 6 was added to the list
i=6, num=5, newnum=[1, 2, 3, 4, 6, 5]  # 5 was added to the list
i=7, num=6, newnum=[1, 2, 3, 4, 6, 5]  # neither 6 or 5 is added, they're there
i=8, num=6, newnum=[1, 2, 3, 4, 6, 5]  # neither 6 or 5 is added, they're there
i=9, num=7, newnum=[1, 2, 3, 4, 6, 5]  # neither 6 or 5 is added, they're there
i=10, num=8, newnum=[1, 2, 3, 4, 6, 5, 7]
i=11, num=9, newnum=[1, 2, 3, 4, 6, 5, 7, 8]
[1, 2, 3, 4, 6, 5, 7, 8, 9]

正如你所看到的,newnum只在循环的最开始是空的,当遇到不在那里的数字(num not in newnum(时,它们会被附加到它。如果一个数字已经在newnum列表中,它就不会再被附加。

列表newnum一开始只是空的。

for的每次迭代期间,它被添加到(append(。

只有在该时间点(not in(不存在新数字的情况下,才会将新数字添加到其中。

因此,它的最终值是经过重复数据消除的数字列表。

number = [1,2,3,4,5,5,6,6,7,8,9]
newnum = []
# For each number in the top list
for num in number:
# If this number is not in the second list
if num not in newnum:
# Add it to the end of the second list
newnum.append(num)
print(newnum)

旁注:一种更简单的方法是使用set,其元素保证是唯一的(如果将同一个数字添加两次,则集合仍然只包含该数字中的一个(。

newnum = list(set(number))

最新更新