2.2 KiB
Difference in import types Python
import x requires dot notation to individuate different components in the module
from x import y
import a component directly from the module removes the need to use dot notation to indviduate
Complex filter function using lambdas
def update_entries(old, new):
"""Merge old and new data, removing dupes"""
combined = old + new
seen = set()
filter_func = lambda x: not (tuple(x) in seen or seen.add(tuple(x)))
unique_combined = list(filter(filter_func, combined))
ChatGpt explanation
Certainly, the line
filter_func = lambda x: not (tuple(x) in seen or seen.add(tuple(x)))
creates a lambda function that takes a single argument x
, where x
is expected to be a list. The function converts x
to a tuple and checks for its existence in the seen
set.
Here is a breakdown of the logic:
-
tuple(x)
: This converts the listx
to a tuple because lists are unhashable and cannot be stored in a set. Tuples, being immutable, can be stored in a set. -
tuple(x) in seen
: This checks whether the tuple form ofx
is already in theseen
set. -
seen.add(tuple(x))
: This adds the tuple form ofx
to theseen
set. Theadd
method of a set returnsNone
. -
tuple(x) in seen or seen.add(tuple(x))
: This combines the above two steps. Theor
operator returns the first "truthy" value it encounters, or the last value otherwise. Sinceseen.add()
returnsNone
, which is "falsy," this part will returnTrue
iftuple(x)
was already inseen
, andNone
otherwise. Importantly, iftuple(x)
was not already inseen
, it will be added. -
not (...)
: Thenot
negates the result. So iftuple(x) in seen
wasTrue
,not True
would beFalse
, causing the filter to skip this item. Iftuple(x) in seen
wasFalse
,not None
would beTrue
, causing the filter to include this item and also adding it toseen
.
In summary, the lambda function acts as a filter that only returns True
for the first occurrence of each unique list x
, after converting it to a tuple for hashability and set membership tests. After a unique list has been seen once, any subsequent occurrences will cause the lambda function to return False
, effectively filtering them out.