两个列表中的第一个公共元素

发布于 2021-01-29 14:58:28

x = [8,2,3,4,5]
y = [6,3,7,2,1]

如何以简洁明了的方式找出两个列表中的第一个公共元素(在本例中为“ 2”)?任何列表都可以为空,也可以没有公共元素-在这种情况下,没有一个很好。

我需要它来向新手展示python,所以越简单越好。

UPD:顺序对于我的目的并不重要,但让我们假设我正在寻找x中的第一个元素,该元素也出现在y中。

关注者
0
被浏览
111
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    这应该很简单 几乎和它一样有效 (要获得更有效的解决方案,请检查Ashwini
    Chaudharys答案,
    以及最有效的检查jamylaks答案和评论):

    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
    

    或者更优雅的事件是封装相同的功能以使用PEP
    8进行工作,例如编码样式约定

    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
    

    而且,如果您需要所有通用元素,可以像这样简单地进行操作:

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看