What is the difference between these two implementations?

Suppose I have a list of lists

S = [list1, list2, ...]

and I want to write a function findsuch that for input the xfunction will look for whether it is xin some sublist S, and then it displays this list or returns Noneid xnot found.

(Note: the intersection of any two subscriptions is empty, so there will be no more than one list.)

My code is very simple:

def find(x):
    for L in S:
        if x in L:
            return L
    return None

But I saw someone write it like this:

def find(x):
    try:
        return next( L for L in S if x in L)
    except StopIteration:
        return None

I wonder what are the differences between the two codes? Is the second preferable to the first? (for example, from the point of view of a software project)

+4
source share
2 answers

, , S, x .

, , next .

, , , for L in S โ†’ if x in L, - for if , - . , .

, . , , ..

return next((L for L in S if x in L), None)

, , None, . , , ? , ", ", .

+2

, . generator, . , , .

, , .

def find_list(x, S):
    ret = [L for L in S if x in L]
    return ret[0] if len(ret) else None

def find_iter(x, S):
    ret = (L for L in S if x in L)
    try:
        return next(ret)
    except StopIteration:
        return None

iPython:

In [1]: S = [["a"], ["b", "c",], ["d"]]

In [2]: %timeit find_list("b", S)
1000000 loops, best of 3: 475 ns per loop

In [3]: %timeit find_list("f", S)
1000000 loops, best of 3: 349 ns per loop

In [4]: %timeit find_iter("b", S)
1000000 loops, best of 3: 802 ns per loop

In [5]: %timeit find_iter("f", S)
100000 loops, best of 3: 1.58 ยตs per loop

by @timgeb, :

def find_iter_opt(x, S):
    ret = (L for L in S if x in L)
    return next(ret, None)

In [8]: %timeit find_iter_opt("b", S)
1000000 loops, best of 3: 751 ns per loop

In [9]: %timeit find_iter_opt("f", S)
1000000 loops, best of 3: 597 ns per loop
-1

All Articles