In [34]: a=[1,2,3] In [35]: b=[6, 8, 2, 5, 3] In [36]: next(ifilter(lambda x: x in b, a), None) Out[36]: 2 In [37]: b=[6, 8, 5] In [38]: next(ifilter(lambda x: x in b, a), None)
Tuesday, January 13, 2015
Python: Find the first true element (i.e. one that matches a condition) in an array
Say you want to check if any value of one array is in another array, and you only care if there is any match at all. Not what the value is, or how many matches there are. Once you have found a match you want to stop processing. Here's a one-liner that will do that and return bool if there is a single match. In my case both arrays already only held unique values.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment