gpt4 book ai didi

python - 两个列表中的第一个公共(public)元素

转载 作者:太空狗 更新时间:2023-10-29 20:32:54 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

这应该是直截了当的并且几乎和它一样有效(更有效的解决方案检查Ashwini Chaudharys answer和最有效的检查jamylaks answer和评论):

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

或者更优雅的事件是将相同的功能封装到 function using 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

如果你想要所有公共(public)元素,你可以像这样简单地做:

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

关于python - 两个列表中的第一个公共(public)元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16118621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com