gpt4 book ai didi

python - 如果在 python 中成功,将元素添加到集合中会返回 true 吗?

转载 作者:太空宇宙 更新时间:2023-11-03 13:01:05 25 4
gpt4 key购买 nike

据我了解,将元素添加到 set 不会返回任何内容。例如:

>>> s=set([1,2,3])
>>> s.add(1)
>>> b = s.add(1)
>>> b
>>> b = s.add(5)
>>> b
>>> print b
None
>>> b = s.add(5)
>>> print b
None

但我很困惑这个函数是如何到remove duplicates of a list while preserving order的作品:

def f7(seq):
seen = set()
seen_add = seen.add
return [ x for x in seq if x not in seen and not seen_add(x)]

not seen_add(x) 总是返回真,无论我是否添加重复项。唯一真正的检查是 x not in seen,因为如果失败,它将不会执行 not see_add(x)

我的理解在这里还是我遗漏了什么?

但是,在这里,如果我添加重复元素或唯一元素,not seen_add(1) 会返回 true。这就很费解了,难道这里的不是只是做空检查吗?但是 seen_add() 没有返回一个集合来进行 empty 检查。为什么 seen_add(2) 不返回任何东西,但 not seen_add(1) 返回 boolean True

>>> seen=set()
>>> seen_add=seen.add
>>> seen_add(1)
>>> seen
set([1])
>>> seen.add(2)
>>> seen
set([1, 2])
>>> not seen_add(1)
True
>>> not seen_add(4)
True

最佳答案

如您所见,seen_add(x) 总是返回 None

现在,not NoneTrue:

>>> not None
True

这在 documentation 中有解释:

5.1. Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • None
  • False
  • ...

由于 not seen_add(x) 始终为 True,因此它对 if 的结果没有影响。它仅用于将x添加到seen的副作用。

换句话说,如下:

seen_add = seen.add
return [ x for x in seq if x not in seen and not seen_add(x)]

是一种更短(并且可能更高效)的编写方式:

result = []
for x in seq:
if x not in seen:
result.append(x)
seen.add(x)
return result

关于python - 如果在 python 中成功,将元素添加到集合中会返回 true 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20891166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com