First common element from two lists

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

    One liner, using next to take the first item from a generator:

    x = [8,2,3,4,5]
    y = [6,3,7,2,1]
    
    first = next((a for a in x if a in y), None)
    

    Or more efficiently since set.__contains__ is faster than list.__contains__:

    set_y = set(y)
    first = next((a for a in x if a in set_y), None)
    

    Or more efficiently but still in one line (don't do this):

    first = next((lambda set_y: a for a in x if a in set_y)(set(y)), None)
    

提交回复
热议问题