First common element from two lists

后端 未结 10 1106
执笔经年
执笔经年 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 14:45

    Use set - this is the generic solution for arbitrary number of lists:

    def first_common(*lsts):
        common = reduce(lambda c, l: c & set(l), lsts[1:], set(lsts[0]))
        if not common:
            return None
        firsts = [min(lst.index(el) for el in common) for lst in lsts]
        index_in_list = min(firsts)
        trgt_lst_index = firsts.index(index_in_list)
        return lsts[trgt_lst_index][index_in_list]
    

    An afterthought - not an effective solution, this one reduces redundant overhead

    def first_common(*lsts):
        common = reduce(lambda c, l: c & set(l), lsts[1:], set(lsts[0]))
        if not common:
            return None
        for lsts_slice in itertools.izip_longest(*lsts):
            slice_intersection = common.intersection(lsts_slice)
            if slice_intersection:
                return slice_intersection.pop()
    

提交回复
热议问题