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 listxto 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 ofxis already in theseenset. -
seen.add(tuple(x)): This adds the tuple form ofxto theseenset. Theaddmethod of a set returnsNone. -
tuple(x) in seen or seen.add(tuple(x)): This combines the above two steps. Theoroperator returns the first "truthy" value it encounters, or the last value otherwise. Sinceseen.add()returnsNone, which is "falsy," this part will returnTrueiftuple(x)was already inseen, andNoneotherwise. Importantly, iftuple(x)was not already inseen, it will be added. -
not (...): Thenotnegates the result. So iftuple(x) in seenwasTrue,not Truewould beFalse, causing the filter to skip this item. Iftuple(x) in seenwasFalse,not Nonewould 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.