Python - 一个列表在另一个列表中的第一次出现
给定两个列表,任务是编写一个Python程序,从列表 2 中提取出现在列表 1 中的第一个元素。
例子:
Input : test_list1 = [1, 6, 3, 7, 8, 9, 2], test_list2 = [4, 10, 8, 2, 0, 11]
Output : 8
Explanation : 8 is first element from list 2, that occurs in list 1, in 5th index.
Input : test_list1 = [1, 6, 3, 7, 8, 9, 2], test_list2 = [4, 10, 18, 12, 0, 11]
Output : None
Explanation : No element of list 2 found in list 1.
方法:使用set() + next()
在此,最初将检查容器转换为设置,并使用 next() 和生成器表达式检查每个元素。 next()函数返回第一个匹配的元素,否则如果没有找到匹配元素,则返回 None 。
Python3
# Python3 code to demonstrate working of
# First occurrence of one list in another
# Using next() + set()
# initializing lists
test_list1 = [1, 6, 3, 7, 8, 9, 2]
test_list2 = [4, 10, 8, 2, 0, 11]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# converting test list to sets
test_list2 = set(test_list2)
# stops when 1st match element is found
res = next((ele for ele in test_list1 if ele in test_list2), None)
# printing result
print("First element in list 1 from 2 : " + str(res))
输出:
The original list 1 is : [1, 6, 3, 7, 8, 9, 2]
The original list 2 is : [4, 10, 8, 2, 0, 11]
First element in list 1 from 2 : 8