Чтобы проверить, совпадают ли два списка в Python, вы можете использовать различные методы. Вот несколько подходов:
-
Метод 1. Сравните списки напрямую с помощью оператора
==.list1 = [1, 2, 3] list2 = [1, 2, 3] if list1 == list2: print("The lists are the same.") else: print("The lists are different.") -
Метод 2. Преобразуйте списки в наборы и сравните их.
list1 = [1, 2, 3] list2 = [3, 2, 1] if set(list1) == set(list2): print("The lists are the same.") else: print("The lists are different.") -
Метод 3: используйте функцию
all()с пониманием списка.list1 = [1, 2, 3] list2 = [1, 2, 3] if all(x == y for x, y in zip(list1, list2)): print("The lists are the same.") else: print("The lists are different.") -
Метод 4. Сравните длину списков и проверьте каждый элемент.
list1 = [1, 2, 3] list2 = [1, 2, 3] if len(list1) == len(list2) and all(x == y for x, y in zip(list1, list2)): print("The lists are the same.") else: print("The lists are different.") -
Метод 5: используйте функцию
numpy.array_equal(), если у вас установлен numpy.import numpy as np list1 = [1, 2, 3] list2 = [1, 2, 3] if np.array_equal(list1, list2): print("The lists are the same.") else: print("The lists are different.")