First common element from two lists

后端 未结 10 1095
执笔经年
执笔经年 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

    This one uses sets. It returns the first common element or None if no common element.

    def findcommon(x,y):
        common = None
        for i in range(0,max(len(x),len(y))):
            common = set(x[0:i]).intersection(set(y[0:i]))
            if common: break
        return list(common)[0] if common else None
    

提交回复
热议问题