简体   繁体   English

为什么列表理解与没有理解的代码的工作方式不同?

[英]Why list comprehension doesn't work the same as code without comprehension?

I tried to create a simple function to remove duplicates from the list.我尝试创建一个简单的 function 以从列表中删除重复项。

x = [7, 7, 5, 6, 8, 9, 9, 0]
for n, i in enumerate(x):
  if i in x[n + 1:]:
    x.remove(i)
print(x)

Output: Output:

[7, 5, 6, 8, 9, 0]

This code works fine as far as I know.据我所知,这段代码运行良好。

But when I'm trying to convert it in comprehension list form, I'm getting wrong output:但是当我试图将它转换为理解列表形式时,我弄错了 output:

def unique_list(lst):
  return [lst.remove(i) for n, i in enumerate(lst) if i in lst[n + 1:]]

x = [7, 7, 5, 6, 8, 9, 9, 0]
print(unique_list(x))

Output: Output:

[None, None]

So, the question is - why the output is different?所以,问题是 - 为什么 output 不同?

a = [1, 2, 3]
deleted = a.remove(1)
print(deleted)
# returns None
print(a)
# returns [2, 3]

.remove() changes the list in place and returns None .remove() 更改列表并返回None

Your two ways of writing the functionality of set(x) are not identical.您编写set(x)功能的两种方式并不相同。 While the first is using a side-effect of x.remove(..) to "return" your modified list in place, the second form returns a newly created list.第一种是使用x.remove(..)的副作用来“返回”您修改后的列表,而第二种形式返回一个新创建的列表。

The elements of that list are formed by what is returned by the expression lst.remove(i) , which is None as Manuel already has pointed out in their answer.该列表的元素由表达式lst.remove(i)返回的内容构成,正如 Manuel 在他们的回答中已经指出的那样,它是None

You receive [None, None] because your code calls lst.remove 2 times.您收到[None, None]因为您的代码调用lst.remove 2 次。 So your function unique_list could be called count_duplicates , just with a peculiar output format (with the length of a list of None encoding the result instead of a straightforward int ).因此,您的 function unique_list可以称为count_duplicates ,只是具有特殊的 output 格式(使用None编码结果而不是直接int的列表的长度)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM