First common element from two lists

后端 未结 10 1061
执笔经年
执笔经年 2020-12-20 14:07
x = [8,2,3,4,5]
y = [6,3,7,2,1]

How to find out the first common element in two lists (in this case, \"2\") in a concise and elegant way? Any list

10条回答
  •  隐瞒了意图╮
    2020-12-20 15:05

    Just for fun (probably not efficient), another version using itertools:

    from itertools import dropwhile, product
    from operator import __ne__
    
    def accept_pair(f):
        "Make a version of f that takes a pair instead of 2 arguments."
        def accepting_pair(pair):
            return f(*pair)
        return accepting_pair
    
    def get_first_common(x, y):
        try:
            # I think this *_ unpacking syntax works only in Python 3
            ((first_common, _), *_) = dropwhile(
                accept_pair(__ne__),
                product(x, y))
        except ValueError:
            return None
        return first_common
    
    x = [8, 2, 3, 4, 5]
    y = [6, 3, 7, 2, 1]
    print(get_first_common(x, y))  # 2
    y = [6, 7, 1]
    print(get_first_common(x, y))  # None
    

    It is simpler, but not as fun, to use lambda pair: pair[0] != pair[1] instead of accept_pair(__ne__).

提交回复
热议问题