Python Code reading collection Introduction ： Why not recommend Python Beginners directly look at the project source code
The code read in this article realizes the function of merging two lists . It also supports the use of a filter condition function , The union of all elements in the list is obtained according to this condition , And the set is the original element of the two lists .
The code snippet read in this article comes from 30-seconds-of-python.
def union_by(a, b, fn): _a = set(map(fn, a)) return list(set(a + [item for item in b if fn(item) not in _a])) # EXAMPLES from math import floor union_by([2.1], [1.2, 2.3], floor) # [2.1, 1.2]
union_by Function receives two lists and a filter condition function . After applying the provided function to each element in both lists , Returns a new list , Contains all non repeating elements that exist in both lists .
map The function has been explained before , It will return an iterator , The iterator will transform the function
fn Apply to all list elements .
Python A special data type , Is an unordered set of non repeating elements . This function is used directly
set Type eliminates duplicate elements in the list .
Special , When the filter condition function is
lamda x:x when , Function to directly find the union of two lists .