Python - 一个列表中另一个列表的第一次出现
当需要在另一个列表中查找一个列表的第一次出现时,可以使用“set”属性和“next”方法。
示例
以下是相同方法的演示
my_list_1 = [23, 64, 34, 77, 89, 9, 21]
my_list_2 = [64, 10, 18, 11, 0, 21]
print("The first list is :")
print(my_list_1)
print("The second list is :")
print(my_list_2)
my_list_2 = set(my_list_2)
my_result = next((ele for ele in my_list_1 if ele in my_list_2), None)
print("The result is :")
print(my_result)输出
The first list is : [23, 64, 34, 77, 89, 9, 21] The second list is : [64, 10, 18, 11, 0, 21] The result is : 64
说明
定义了两个列表,并显示在控制台上。
第二个列表被转换为一个集合。
这样,保留了所有唯一元素。
将消除重复元素。
“next”方法用于通过遍历第一个和第二个列表来迭代到下一个值。
此输出被分配给一个变量。
这作为输出显示在控制台上。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP