我是 Python3.3 的新手,我想从列表中消除重复的成员,我在网上找到了这段简短的代码,但我不知道这段代码背后的逻辑是什么?尤其是“not seen_add(x)”部分!
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)]
有人能帮我解决这个问题吗?!
此代码是一种简洁的方法,可以从列表中删除重复项,同时保持元素的顺序。让我们分解一下:
def f7(seq): seen = set() # This will store the unique elements we've encountered so far seen_add = seen.add # A shorthand reference to the `add` method of the set (for performance reasons) # List comprehension to build a list of unique elements return [x for x in seq if x not in seen and not seen_add(x)]
以下是具体情况:
seen = set()
x in seen
seen_add = seen.add
add
seen_add(x)
seen.add(x)
x not in seen
x
seen
not seen_add(x)
f7([1, 2, 2, 3, 4, 1, 5, 3])
输出:[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
此函数删除重复项,同时保留元素的原始顺序。