这应该很简单 几乎和它一样有效 (要获得更有效的解决方案,请检查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]



