如何比较Python中两个列表的元素?
本文介绍了比较Python中两个列表的元素的不同方法。要比较两个列表,我们比较一个列表中的数据项和另一个列表中的数据项,并检查它们是否相同。
下面是两个相似的列表。
List_1 = [1,2,3,4,5,6,7]
List_2 = [1,2,3,4,5,6,7]
上面两个列表的输出结果应为相同。
更多Python相关文章,请阅读:Python 教程
使用set()方法和运算符
在这种方法中,我们使用 set() 方法和 运算符来比较两个列表的元素。Python的 set() 方法可以将列表转换为集合,而不考虑项目的顺序。我们还使用等于运算符()来比较列表的数据项。
示例
在下面的示例中,将比较两个列表。我们将列表转换为集合并使用 运算符逐个比较元素。如果两个列表中的所有元素都相等,则执行该块,并显示结果。
list_1 = [1, 2, 3, 4, 5]
list_2 = [2, 3, 1, 5, 4]
a = set(list_1)
b = set(list_2)
if a == b:
print("The list_1 and list_2 are equal")
else:
print("The list_1 and list_2 are not equal")
输出
执行上述程序的输出结果如下。
The list_1 and list_2 are equal
使用sort()方法和运算符
在这种方法中,我们使用 sort() 方法和运算符来比较两个列表的元素。Python提供的 sort() 方法用于按升序或降序对列表的元素进行排序。排序列表后,我们使用运算符比较列表。相同的元素在两个列表的相同索引位置,这意味着列表相等。
示例
在下面的示例中,我们首先使用 sort() 方法对列表的元素进行排序,然后使用运算符比较列表。
list_1 = [1, 2, 3, 4, 5]
list_2 = [2, 3, 1, 5, 4]
list_3 = [1, 5, 6, 3, 4]
list_1.sort()
list_2.sort()
list_3.sort()
if list_1 == list_2:
print("The list_1 and list_2 are the same")
else:
print("The list_1 and list_2 are not the same")
if list_1 == list_3:
print("The list_1 and list_3 are the same")
else:
print("The list_1 and list_3 are not the same")
输出
上述代码输出如下。
The list_1 and list_2 are the same
The list_1 and list_3 are not the same
使用map()和reduce()方法
我们需要导入functools来使用 map() 和 reduce() 方法。
map() 函数接受两个参数:一个函数和一个Python可迭代对象(列表、元组、字符串等),并返回一个映射对象。函数应用于每个列表元素并返回一个迭代器。
此外, reduce() 方法递归地将指定函数应用于可迭代对象。
在这种情况下我们将结合两种策略。使用 map() 方法将函数(可以是用户定义的或lambda函数)应用于每个可迭代对象,使用 reduce() 函数处理递归应用。
例子
以下是使用 map() 和 reduce() 方法比较两个列表的示例代码。
import functools
list1 = [1, 2, 3, 4, 5]
list2 = [1, 5, 6, 3, 4]
list3 = [2, 3, 1, 5, 4]
if functools.reduce(lambda x, y: x and y, map(lambda a, b: a == b, list1, list2), True):
print("list1和list2相同")
else:
print("list1和list2不相同")
if functools.reduce(lambda x, y: x and y, map(lambda a, b: a == b, list1, list3), True):
print("list1和list3相同")
else:
print("list1和list3不相同")
输出结果
以上代码的输出结果如下。
list1和list2不相同
list1和list3相同