First common element from two lists

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

    This should be straight forward and almost as effective as it gets (for more effective solution check Ashwini Chaudharys answer and for the most effective check jamylaks answer and comments):

    result = None
    # Go trough one array
    for i in x:
    
        # The element repeats in the other list...
        if i in y:
    
            # Store the result and break the loop
            result = i
            break
    

    Or event more elegant would be to encapsulate the same functionality to functionusing PEP 8 like coding style conventions:

    def get_first_common_element(x,y):
        ''' Fetches first element from x that is common for both lists
            or return None if no such an element is found.
        '''
        for i in x:
            if i in y:
                return i
    
        # In case no common element found, you could trigger Exception
        # Or if no common element is _valid_ and common state of your application
        # you could simply return None and test return value
        # raise Exception('No common element found')
        return None
    

    And if you want all common elements you can do it simply like this:

    >>> [i for i in x if i in y]
    [1, 2, 3]
    

提交回复
热议问题