栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

result = None# Go trough one arrayfor 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]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/429263.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号