Hướng dẫn fastest way to compare two lists python - cách nhanh nhất để so sánh hai danh sách python

Một bài kiểm tra hiệu suất nhanh hiển thị giải pháp của Lutz là tốt nhất:

import time def speed_test(func): def wrapper(*args, **kwargs): t1 = time.time() for x in xrange(5000): results = func(*args, **kwargs) t2 = time.time() print '%s took %0.3f ms' % (func.func_name, (t2-t1)*1000.0) return results return wrapper @speed_test def compare_bitwise(x, y): set_x = frozenset(x) set_y = frozenset(y) return set_x & set_y @speed_test def compare_listcomp(x, y): return [i for i, j in zip(x, y) if i == j] @speed_test def compare_intersect(x, y): return frozenset(x).intersection(y) # Comparing short lists a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] compare_bitwise(a, b) compare_listcomp(a, b) compare_intersect(a, b) # Comparing longer lists import random a = random.sample(xrange(100000), 10000) b = random.sample(xrange(100000), 10000) compare_bitwise(a, b) compare_listcomp(a, b) compare_intersect(a, b)

Đây là những kết quả trên máy của tôi:

# Short list: compare_bitwise took 10.145 ms compare_listcomp took 11.157 ms compare_intersect took 7.461 ms # Long list: compare_bitwise took 11203.709 ms compare_listcomp took 17361.736 ms compare_intersect took 6833.768 ms

Rõ ràng, bất kỳ thử nghiệm hiệu suất nhân tạo nào cũng nên được thực hiện với một hạt muối, nhưng vì câu trả lời >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 5 ít nhất là nhanh như các giải pháp khác, và cũng dễ đọc nhất, nó nên là giải pháp tiêu chuẩn cho vấn đề phổ biến này.

Cách đây một thời gian, tôi đã viết một hướng dẫn về cách so sánh hai từ điển trong Python 3 và làm thế nào nhiệm vụ này không đơn giản như nó có thể nghe. Hóa ra so sánh hai danh sách trong Python rất khó khăn khi so sánh >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 6s.

Cách chúng tôi được dạy để so sánh hai đối tượng trong Python là một chút sai lệch. Hầu hết các cuốn sách và hướng dẫn đều dạy so sánh đối tượng bằng cách sử dụng toán tử >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 7 hoặc >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 8. Trong thực tế, hai nhà khai thác này chỉ bao gồm một phần nhỏ các trường hợp sử dụng thường xuyên nhất.

Ví dụ:

  • Điều gì sẽ xảy ra nếu chúng ta muốn so sánh một danh sách các số điểm nổi xem xét một dung sai nhất định?
  • Điều gì sẽ xảy ra nếu chúng ta muốn đối chiếu hai danh sách nhưng bỏ qua thứ tự xuất hiện các yếu tố?
  • Có lẽ chúng ta cần so sánh hai danh sách và trả về các yếu tố giao nhau
  • Đôi khi chúng ta có thể muốn có được sự khác biệt giữa hai danh sách
  • Điều gì sẽ xảy ra nếu chúng ta có hai danh sách các chuỗi và cần so sánh chúng bằng cách bỏ qua các trường hợp chuỗi?
  • Điều gì sẽ xảy ra nếu chúng ta cung cấp một danh sách các mảng >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 9 để so sánh nhau, chúng ta có thể làm gì?
  • Hoặc có thể chúng tôi có một danh sách các đối tượng tùy chỉnh hoặc danh sách từ điển.

Danh sách này cứ lặp đi lặp lại, và đối với tất cả các trường hợp sử dụng này bằng cách sử dụng >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 7 không giúp ích gì.

Đó là những gì chúng ta sẽ thấy trong bài viết này. Chúng tôi sẽ học các cách tốt nhất để so sánh hai danh sách trong Python cho một số trường hợp sử dụng trong đó toán tử >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 7 là không đủ.

Sẳn sàng? Đi nào!

So sánh nếu hai danh sách bằng nhau trong Python

Cách dễ nhất để so sánh hai danh sách cho bình đẳng là sử dụng toán tử >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 7. Phương pháp so sánh này hoạt động tốt cho các trường hợp đơn giản, nhưng như chúng ta sẽ thấy sau, nó không hoạt động với các so sánh nâng cao.

Một ví dụ về một trường hợp đơn giản sẽ là danh sách các đối tượng >>> numbers = [] >>> numbers.append(0.1 + 0.1 + 0.1) # derive the element based on a summation >>> numbers.append(0.2) # add a single element >>> target = [0.3, 0.2] >>> numbers == target # compares the lists False >>> numbers # Ooopppssss.... [0.30000000000000004, 0.2] >>> target [0.3, 0.2] 3 hoặc >>> numbers = [] >>> numbers.append(0.1 + 0.1 + 0.1) # derive the element based on a summation >>> numbers.append(0.2) # add a single element >>> target = [0.3, 0.2] >>> numbers == target # compares the lists False >>> numbers # Ooopppssss.... [0.30000000000000004, 0.2] >>> target [0.3, 0.2] 4.

>>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False

Khá đơn giản, phải không? Thật không may, thế giới rất phức tạp, và mã cấp sản xuất cũng vậy. Trong thế giới thực, mọi thứ trở nên phức tạp thực sự nhanh chóng. Như một minh họa, hãy xem xét các trường hợp sau đây.

Giả sử bạn có một danh sách các điểm nổi được xây dựng động. Bạn có thể thêm các phần tử đơn hoặc các yếu tố có nguồn gốc từ một hoạt động toán học như >>> numbers = [] >>> numbers.append(0.1 + 0.1 + 0.1) # derive the element based on a summation >>> numbers.append(0.2) # add a single element >>> target = [0.3, 0.2] >>> numbers == target # compares the lists False >>> numbers # Ooopppssss.... [0.30000000000000004, 0.2] >>> target [0.3, 0.2] 5.

>>> numbers = [] >>> numbers.append(0.1 + 0.1 + 0.1) # derive the element based on a summation >>> numbers.append(0.2) # add a single element >>> target = [0.3, 0.2] >>> numbers == target # compares the lists False >>> numbers # Ooopppssss.... [0.30000000000000004, 0.2] >>> target [0.3, 0.2]

Rõ ràng, số học điểm nổi có những hạn chế của nó và đôi khi chúng tôi muốn so sánh hai danh sách nhưng bỏ qua các lỗi chính xác hoặc thậm chí xác định một số dung sai. Đối với các trường hợp như thế này, nhà điều hành >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 7 đã giành chiến thắng.

Mọi thứ có thể trở nên phức tạp hơn nếu danh sách có các đối tượng hoặc đối tượng tùy chỉnh từ các thư viện khác, chẳng hạn như >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 9.

In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Bạn cũng có thể muốn so sánh các danh sách và trả về các trận đấu. Hoặc có thể so sánh hai danh sách và trả về sự khác biệt. Hoặc có lẽ bạn muốn so sánh hai danh sách bỏ qua các bản sao hoặc so sánh danh sách các từ điển trong Python.

Trong mọi trường hợp, sử dụng >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 7 không phải là câu trả lời và đó là những gì chúng ta sẽ thấy tiếp theo: Cách thực hiện các hoạt động so sánh phức tạp giữa hai danh sách trong Python.

So sánh hai danh sách các số float

Trong phần trước, chúng tôi đã thấy rằng số học điểm nổi có thể gây ra lỗi chính xác. Nếu chúng tôi có một danh sách các phao và muốn so sánh nó với một danh sách khác, rất có thể nhà điều hành >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 7 sẽ không giúp đỡ.

Hãy xem lại ví dụ từ phần trước và xem cách tốt nhất để so sánh hai danh sách phao.

>>> numbers = [] >>> numbers.append(0.1 + 0.1 + 0.1) # derive the element based on a summation >>> numbers.append(0.2) # add a single element >>> target = [0.3, 0.2] >>> numbers == target # compares the lists False >>> numbers # Ooopppssss.... [0.30000000000000004, 0.2] >>> target [0.3, 0.2]

Như bạn thấy, In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 0, khiến việc so sánh thất bại. Bây giờ, làm thế nào chúng ta có thể làm tốt hơn? Nó thậm chí có thể?

Có một vài cách để tiếp cận nhiệm vụ này. Một người sẽ là tạo chức năng tùy chỉnh của riêng chúng tôi, lặp đi lặp lại các yếu tố và so sánh từng cái một bằng cách sử dụng hàm In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 1.

May mắn thay, chúng ta không phải phát minh lại bánh xe. Như tôi đã trình bày trong bài viết "Cách so sánh hai dicts", chúng ta có thể sử dụng một thư viện có tên In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 2 cho điều đó. Thư viện này hỗ trợ các loại đối tượng và danh sách khác nhau là một trong số đó.

Ví dụ dưới đây bắt đầu bằng cách thiết lập hai danh sách chúng tôi muốn so sánh. Sau đó, chúng tôi chuyển nó cho hàm tạo In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 3 trả về sự khác biệt. Thật tuyệt, giá trị trả lại có nhiều thông tin hơn nhiều so với một boolean đơn giản.

Vì chúng tôi muốn bỏ qua lỗi chính xác, chúng tôi có thể đặt số chữ số sau khi điểm thập phân sẽ được sử dụng trong so sánh.

Kết quả là một chế độ trống, có nghĩa là các danh sách là bằng nhau. Nếu chúng tôi thử so sánh một danh sách với số float khác nhau với hơn 3 chữ số quan trọng, thư viện sẽ trả về sự khác biệt đó.

Để tái lập, trong bài viết này, tôi đã sử dụng phiên bản mới nhất của In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 2 là In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 5.

In [1]: from deepdiff import DeepDiff In [2]: numbers = [] In [3]: numbers.append(0.1 + 0.1 + 0.1) # derive the element based on a summation In [4]: numbers.append(0.2) # add a single element In [5]: target = [0.3, 0.2] # if we don't specify the number of significant digits, the comparison will use == In [6]: DeepDiff(numbers, target) Out[6]: {'values_changed': {'root[0]': {'new_value': 0.3, 'old_value': 0.30000000000000004}}} # 0.30000000000000004 and 0.3 are equal if we only look at the first 3 significant digits In [7]: DeepDiff(numbers, target, significant_digits=3) Out[7]: {} In [8]: numbers Out[8]: [0.30000000000000004, 0.2] In [9]: target = [0.341, 0.2] # 0.341 differs in more than 3 significant digits In [10]: DeepDiff(numbers, target, significant_digits=3) Out[10]: {'values_changed': {'root[0]': {'new_value': 0.341, 'old_value': 0.30000000000000004}}}

So sánh nếu hai danh sách không có thứ tự (danh sách không có thứ tự) bằng nhau

Danh sách trong Python không được đặt hàng theo mặc định. Đôi khi chúng tôi muốn so sánh hai danh sách nhưng đối xử với chúng giống như chúng có cùng các yếu tố, bất kể thứ tự của chúng.

Có hai cách để làm điều này:

  • Sắp xếp danh sách và sử dụng toán tử >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 7
  • Chuyển đổi chúng thành In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 7S và sử dụng toán tử >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 7
  • Sử dụng In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 2

Hai phương pháp đầu tiên này giả định các yếu tố có thể được so sánh một cách an toàn khi sử dụng toán tử ____27. Cách tiếp cận này không hoạt động cho các số điểm nổi và các đối tượng phức tạp khác, nhưng như chúng ta đã thấy trong phần trước, chúng ta có thể sử dụng In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 2.

Sắp xếp danh sách và sử dụng toán tử >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 7

Bạn có thể sắp xếp danh sách trong Python theo hai cách khác nhau:

  • Sử dụng phương pháp >>> numbers = [] >>> numbers.append(0.1 + 0.1 + 0.1) # derive the element based on a summation >>> numbers.append(0.2) # add a single element >>> target = [0.3, 0.2] >>> numbers == target # compares the lists False >>> numbers # Ooopppssss.... [0.30000000000000004, 0.2] >>> target [0.3, 0.2] 3
  • sử dụng chức năng >>> numbers = [] >>> numbers.append(0.1 + 0.1 + 0.1) # derive the element based on a summation >>> numbers.append(0.2) # add a single element >>> target = [0.3, 0.2] >>> numbers == target # compares the lists False >>> numbers # Ooopppssss.... [0.30000000000000004, 0.2] >>> target [0.3, 0.2] 4

Phương pháp đầu tiên sắp xếp một danh sách tại chỗ và điều đó có nghĩa là danh sách của bạn sẽ được sửa đổi. Bạn nên không sửa đổi danh sách tại chỗ vì nó có thể giới thiệu các lỗi khó phát hiện.

Sử dụng >>> numbers = [] >>> numbers.append(0.1 + 0.1 + 0.1) # derive the element based on a summation >>> numbers.append(0.2) # add a single element >>> target = [0.3, 0.2] >>> numbers == target # compares the lists False >>> numbers # Ooopppssss.... [0.30000000000000004, 0.2] >>> target [0.3, 0.2] 5 tốt hơn vì nó trả về một danh sách mới và giữ cho bản gốc không được sửa đổi.

Hãy xem nó hoạt động như thế nào.

In [6]: numbers = [10, 30, 20] In [7]: target = [10, 20, 30] In [8]: numbers == target Out[8]: False In [9]: sorted(numbers) == sorted(target) Out[9]: True In [10]: sorted(numbers) Out[10]: [10, 20, 30] In [11]: sorted(target) Out[11]: [10, 20, 30]

Do đó, bằng cách sắp xếp các danh sách trước tiên, chúng tôi đảm bảo rằng cả hai danh sách sẽ có cùng một thứ tự và do đó có thể được so sánh bằng cách sử dụng toán tử >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 7.

Chuyển đổi >>> numbers = [] >>> numbers.append(0.1 + 0.1 + 0.1) # derive the element based on a summation >>> numbers.append(0.2) # add a single element >>> target = [0.3, 0.2] >>> numbers == target # compares the lists False >>> numbers # Ooopppssss.... [0.30000000000000004, 0.2] >>> target [0.3, 0.2] 7S thành In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 7

Trái ngược với danh sách, các bộ trong Python don lồng quan tâm đến trật tự. Ví dụ: một tập hợp >>> numbers = [] >>> numbers.append(0.1 + 0.1 + 0.1) # derive the element based on a summation >>> numbers.append(0.2) # add a single element >>> target = [0.3, 0.2] >>> numbers == target # compares the lists False >>> numbers # Ooopppssss.... [0.30000000000000004, 0.2] >>> target [0.3, 0.2] 9 giống như In [1]: from deepdiff import DeepDiff In [2]: numbers = [] In [3]: numbers.append(0.1 + 0.1 + 0.1) # derive the element based on a summation In [4]: numbers.append(0.2) # add a single element In [5]: target = [0.3, 0.2] # if we don't specify the number of significant digits, the comparison will use == In [6]: DeepDiff(numbers, target) Out[6]: {'values_changed': {'root[0]': {'new_value': 0.3, 'old_value': 0.30000000000000004}}} # 0.30000000000000004 and 0.3 are equal if we only look at the first 3 significant digits In [7]: DeepDiff(numbers, target, significant_digits=3) Out[7]: {} In [8]: numbers Out[8]: [0.30000000000000004, 0.2] In [9]: target = [0.341, 0.2] # 0.341 differs in more than 3 significant digits In [10]: DeepDiff(numbers, target, significant_digits=3) Out[10]: {'values_changed': {'root[0]': {'new_value': 0.341, 'old_value': 0.30000000000000004}}} 0. Do đó, chúng ta có thể sử dụng tính năng này để so sánh hai danh sách bỏ qua thứ tự các yếu tố.

Để làm như vậy, chúng tôi chuyển đổi từng danh sách thành một tập hợp, sau đó sử dụng >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 7 để so sánh chúng.

In [12]: numbers = [10, 30, 20] In [13]: target = [10, 20, 30] In [14]: set(numbers) == set(target) Out[14]: True In [15]: set(numbers) Out[15]: {10, 20, 30} In [16]: set(target) Out[16]: {10, 20, 30}

Sử dụng thư viện In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 2

Thư viện này cũng cho phép chúng tôi bỏ qua thứ tự theo trình tự như >>> numbers = [] >>> numbers.append(0.1 + 0.1 + 0.1) # derive the element based on a summation >>> numbers.append(0.2) # add a single element >>> target = [0.3, 0.2] >>> numbers == target # compares the lists False >>> numbers # Ooopppssss.... [0.30000000000000004, 0.2] >>> target [0.3, 0.2] 7s. Theo mặc định, nó sẽ xem xét thứ tự, nhưng nếu chúng tôi đặt In [1]: from deepdiff import DeepDiff In [2]: numbers = [] In [3]: numbers.append(0.1 + 0.1 + 0.1) # derive the element based on a summation In [4]: numbers.append(0.2) # add a single element In [5]: target = [0.3, 0.2] # if we don't specify the number of significant digits, the comparison will use == In [6]: DeepDiff(numbers, target) Out[6]: {'values_changed': {'root[0]': {'new_value': 0.3, 'old_value': 0.30000000000000004}}} # 0.30000000000000004 and 0.3 are equal if we only look at the first 3 significant digits In [7]: DeepDiff(numbers, target, significant_digits=3) Out[7]: {} In [8]: numbers Out[8]: [0.30000000000000004, 0.2] In [9]: target = [0.341, 0.2] # 0.341 differs in more than 3 significant digits In [10]: DeepDiff(numbers, target, significant_digits=3) Out[10]: {'values_changed': {'root[0]': {'new_value': 0.341, 'old_value': 0.30000000000000004}}} 4 thành In [1]: from deepdiff import DeepDiff In [2]: numbers = [] In [3]: numbers.append(0.1 + 0.1 + 0.1) # derive the element based on a summation In [4]: numbers.append(0.2) # add a single element In [5]: target = [0.3, 0.2] # if we don't specify the number of significant digits, the comparison will use == In [6]: DeepDiff(numbers, target) Out[6]: {'values_changed': {'root[0]': {'new_value': 0.3, 'old_value': 0.30000000000000004}}} # 0.30000000000000004 and 0.3 are equal if we only look at the first 3 significant digits In [7]: DeepDiff(numbers, target, significant_digits=3) Out[7]: {} In [8]: numbers Out[8]: [0.30000000000000004, 0.2] In [9]: target = [0.341, 0.2] # 0.341 differs in more than 3 significant digits In [10]: DeepDiff(numbers, target, significant_digits=3) Out[10]: {'values_changed': {'root[0]': {'new_value': 0.341, 'old_value': 0.30000000000000004}}} 5, thì tất cả chúng ta đều tốt. Hãy xem điều này trong hành động.

In [11]: numbers = [10, 30, 20] In [12]: target = [10, 20, 30] In [13]: DeepDiff(numbers, target) Out[13]: {'values_changed': {'root[1]': {'new_value': 20, 'old_value': 30}, 'root[2]': {'new_value': 30, 'old_value': 20}}} In [14]: DeepDiff(numbers, target, ignore_order=True) Out[14]: {}

Sử dụng In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 2 có ưu và nhược điểm. Cuối cùng, đó là một thư viện bên ngoài bạn cần cài đặt, vì vậy nếu bạn có thể sử dụng In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 7 để so sánh các danh sách, thì hãy gắn bó với nó. Tuy nhiên, nếu bạn có các trường hợp sử dụng khác mà nó có thể tỏa sáng, thì tôi sẽ đi với nó.

Cách so sánh hai danh sách và các trận đấu trở lại

Trong phần này, chúng ta sẽ xem cách chúng ta có thể so sánh hai danh sách và tìm giao điểm của chúng. Nói cách khác, chúng tôi muốn tìm các giá trị xuất hiện trong cả hai.

Để làm điều đó, chúng ta có thể một lần nữa sử dụng In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 7 và thực hiện giao lộ của họ.

# Short list: compare_bitwise took 10.145 ms compare_listcomp took 11.157 ms compare_intersect took 7.461 ms # Long list: compare_bitwise took 11203.709 ms compare_listcomp took 17361.736 ms compare_intersect took 6833.768 ms 0

Cách so sánh hai danh sách trong Python và trả về sự khác biệt

Chúng ta có thể tìm thấy sự khác biệt giữa hai danh sách trong Python theo hai cách khác nhau:

  • Sử dụng In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 7
  • Sử dụng thư viện ____42

Sử dụng In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 7

Giống như chúng tôi đã làm để xác định giao điểm, chúng tôi có thể tận dụng cấu trúc dữ liệu In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 7 để kiểm tra sự khác biệt giữa hai danh sách trong Python.

Nếu chúng ta muốn có được tất cả các yếu tố có mặt trong danh sách đầu tiên nhưng không phải trong phần thứ hai, chúng ta có thể sử dụng In [6]: numbers = [10, 30, 20] In [7]: target = [10, 20, 30] In [8]: numbers == target Out[8]: False In [9]: sorted(numbers) == sorted(target) Out[9]: True In [10]: sorted(numbers) Out[10]: [10, 20, 30] In [11]: sorted(target) Out[11]: [10, 20, 30] 3.

Mặt khác, nếu chúng ta muốn tìm tất cả các yếu tố trong một trong hai danh sách nhưng không phải cả hai, thì chúng ta có thể sử dụng In [6]: numbers = [10, 30, 20] In [7]: target = [10, 20, 30] In [8]: numbers == target Out[8]: False In [9]: sorted(numbers) == sorted(target) Out[9]: True In [10]: sorted(numbers) Out[10]: [10, 20, 30] In [11]: sorted(target) Out[11]: [10, 20, 30] 4.

# Short list: compare_bitwise took 10.145 ms compare_listcomp took 11.157 ms compare_intersect took 7.461 ms # Long list: compare_bitwise took 11203.709 ms compare_listcomp took 17361.736 ms compare_intersect took 6833.768 ms 1

Phương pháp này có một giới hạn: Nó nhóm những gì khác biệt giữa các danh sách thành một kết quả cuối cùng là sự khác biệt đã đặt. Điều gì sẽ xảy ra nếu chúng ta muốn biết những yếu tố nào trong sự khác biệt đó thuộc về danh sách nào?

Sử dụng In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 2

Như chúng ta đã thấy cho đến nay, thư viện này rất mạnh mẽ và nó trả về một sự khác biệt đẹp. Hãy xem những gì xảy ra khi chúng ta sử dụng In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 2 để có được sự khác biệt giữa hai danh sách trong Python.

# Short list: compare_bitwise took 10.145 ms compare_listcomp took 11.157 ms compare_intersect took 7.461 ms # Long list: compare_bitwise took 11203.709 ms compare_listcomp took 17361.736 ms compare_intersect took 6833.768 ms 2

Theo đó, In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 2 trả về những gì đã thay đổi từ danh sách này sang danh sách khác. Cách tiếp cận đúng sau đó sẽ phụ thuộc vào trường hợp sử dụng của bạn. Nếu bạn muốn có một sự khác biệt chi tiết, thì hãy sử dụng In [6]: numbers = [10, 30, 20] In [7]: target = [10, 20, 30] In [8]: numbers == target Out[8]: False In [9]: sorted(numbers) == sorted(target) Out[9]: True In [10]: sorted(numbers) Out[10]: [10, 20, 30] In [11]: sorted(target) Out[11]: [10, 20, 30] 8. Nếu không, chỉ cần sử dụng In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 7.

Cách so sánh hai danh sách các chuỗi

So sánh hai danh sách chuỗi trong Python phụ thuộc phần lớn vào loại so sánh bạn muốn thực hiện. Đó là bởi vì chúng ta có thể so sánh một chuỗi theo một số cách.

Trong phần này, chúng ta sẽ thấy 3 cách khác nhau để làm điều đó.

Đơn giản nhất là sử dụng toán tử >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 7, như chúng ta đã thấy lúc đầu. Phương pháp này phù hợp nếu bạn muốn so sánh nghiêm ngặt giữa mỗi chuỗi.

# Short list: compare_bitwise took 10.145 ms compare_listcomp took 11.157 ms compare_intersect took 7.461 ms # Long list: compare_bitwise took 11203.709 ms compare_listcomp took 17361.736 ms compare_intersect took 6833.768 ms 3

Mọi thứ bắt đầu trở nên lộn xộn nếu bạn muốn so sánh danh sách các chuỗi nhưng bỏ qua vụ án. Sử dụng >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 7 cho điều đó không hoạt động.

# Short list: compare_bitwise took 10.145 ms compare_listcomp took 11.157 ms compare_intersect took 7.461 ms # Long list: compare_bitwise took 11203.709 ms compare_listcomp took 17361.736 ms compare_intersect took 6833.768 ms 4

Công cụ tốt nhất cho điều đó là một lần nữa In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 2. Nó cho phép chúng ta bỏ qua chuỗi bằng cách chuyển một lá cờ boolean cho nó.

# Short list: compare_bitwise took 10.145 ms compare_listcomp took 11.157 ms compare_intersect took 7.461 ms # Long list: compare_bitwise took 11203.709 ms compare_listcomp took 17361.736 ms compare_intersect took 6833.768 ms 5

Chúng ta cũng có thể bỏ qua thứ tự trong đó các chuỗi xuất hiện trong danh sách.

# Short list: compare_bitwise took 10.145 ms compare_listcomp took 11.157 ms compare_intersect took 7.461 ms # Long list: compare_bitwise took 11203.709 ms compare_listcomp took 17361.736 ms compare_intersect took 6833.768 ms 6

Bạn cũng có thể đi xa hơn và thực hiện các so sánh nâng cao bằng cách chuyển một toán tử tùy chỉnh cho In [6]: numbers = [10, 30, 20] In [7]: target = [10, 20, 30] In [8]: numbers == target Out[8]: False In [9]: sorted(numbers) == sorted(target) Out[9]: True In [10]: sorted(numbers) Out[10]: [10, 20, 30] In [11]: sorted(target) Out[11]: [10, 20, 30] 8.

Ví dụ, giả sử bạn muốn so sánh các chuỗi nhưng bỏ qua bất kỳ khoảng trắng nào họ có thể có.

Hoặc có lẽ bạn muốn thực hiện một kết hợp mờ bằng số liệu EDIT khoảng cách.

Để làm điều đó, chúng ta có thể viết logic so sánh trong lớp toán tử và chuyển nó sang In [6]: numbers = [10, 30, 20] In [7]: target = [10, 20, 30] In [8]: numbers == target Out[8]: False In [9]: sorted(numbers) == sorted(target) Out[9]: True In [10]: sorted(numbers) Out[10]: [10, 20, 30] In [11]: sorted(target) Out[11]: [10, 20, 30] 8.

Trong ví dụ đầu tiên này, chúng tôi sẽ bỏ qua bất kỳ khoảng trắng nào bằng cách cắt các chuỗi trước khi so sánh chúng.

# Short list: compare_bitwise took 10.145 ms compare_listcomp took 11.157 ms compare_intersect took 7.461 ms # Long list: compare_bitwise took 11203.709 ms compare_listcomp took 17361.736 ms compare_intersect took 6833.768 ms 7

Sau đó, chúng ta chỉ có thể cắm vào In [6]: numbers = [10, 30, 20] In [7]: target = [10, 20, 30] In [8]: numbers == target Out[8]: False In [9]: sorted(numbers) == sorted(target) Out[9]: True In [10]: sorted(numbers) Out[10]: [10, 20, 30] In [11]: sorted(target) Out[11]: [10, 20, 30] 8 bằng cách thêm nó vào danh sách In [12]: numbers = [10, 30, 20] In [13]: target = [10, 20, 30] In [14]: set(numbers) == set(target) Out[14]: True In [15]: set(numbers) Out[15]: {10, 20, 30} In [16]: set(target) Out[16]: {10, 20, 30} 6, như vậy In [12]: numbers = [10, 30, 20] In [13]: target = [10, 20, 30] In [14]: set(numbers) == set(target) Out[14]: True In [15]: set(numbers) Out[15]: {10, 20, 30} In [16]: set(target) Out[16]: {10, 20, 30} 7.

# Short list: compare_bitwise took 10.145 ms compare_listcomp took 11.157 ms compare_intersect took 7.461 ms # Long list: compare_bitwise took 11203.709 ms compare_listcomp took 17361.736 ms compare_intersect took 6833.768 ms 8

Cách so sánh hai danh sách từ điển

So sánh hai danh sách từ điển trong Python chắc chắn là phức tạp mà không có sự trợ giúp của một thư viện bên ngoài. Như chúng ta đã thấy cho đến nay, In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 2 là đủ linh hoạt và chúng ta có thể sử dụng nó để so sánh các đối tượng phức tạp sâu như danh sách từ điển.

Hãy xem những gì xảy ra khi chúng ta vượt qua hai danh sách từ điển.

# Short list: compare_bitwise took 10.145 ms compare_listcomp took 11.157 ms compare_intersect took 7.461 ms # Long list: compare_bitwise took 11203.709 ms compare_listcomp took 17361.736 ms compare_intersect took 6833.768 ms 9

Nó xuất ra vị trí chính xác nơi các yếu tố khác nhau và sự khác biệt là gì!

Hãy xem một ví dụ khác trong đó một danh sách có một phần tử bị thiếu.

>>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 0

Nó nói rằng từ điển thứ hai đã bị xóa, đó là trường hợp cho ví dụ này.

Cách so sánh hai danh sách danh sách

So sánh danh sách đa chiều của A.K.A Danh sách các danh sách là dễ dàng cho In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 2. Nó hoạt động giống như một danh sách các >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 6s.

Trong ví dụ dưới đây, chúng tôi có hai danh sách đa chiều mà chúng tôi muốn so sánh. Khi được chuyển đến In [6]: numbers = [10, 30, 20] In [7]: target = [10, 20, 30] In [8]: numbers == target Out[8]: False In [9]: sorted(numbers) == sorted(target) Out[9]: True In [10]: sorted(numbers) Out[10]: [10, 20, 30] In [11]: sorted(target) Out[11]: [10, 20, 30] 8, nó sẽ trả về vị trí chính xác mà các yếu tố khác nhau.

Ví dụ, đối với vị trí In [11]: numbers = [10, 30, 20] In [12]: target = [10, 20, 30] In [13]: DeepDiff(numbers, target) Out[13]: {'values_changed': {'root[1]': {'new_value': 20, 'old_value': 30}, 'root[2]': {'new_value': 30, 'old_value': 20}}} In [14]: DeepDiff(numbers, target, ignore_order=True) Out[14]: {} 2, giá trị mới là 8 và cũ là 3. Một khía cạnh thú vị khác là nó hoạt động cho các cấu trúc được lồng sâu, ví dụ, In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 2 cũng nêu bật sự khác biệt ở vị trí In [11]: numbers = [10, 30, 20] In [12]: target = [10, 20, 30] In [13]: DeepDiff(numbers, target) Out[13]: {'values_changed': {'root[1]': {'new_value': 20, 'old_value': 30}, 'root[2]': {'new_value': 30, 'old_value': 20}}} In [14]: DeepDiff(numbers, target, ignore_order=True) Out[14]: {} 4.

>>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 1

Khi cung cấp cho thư viện bằng hai danh sách đa chiều giống hệt nhau, nó sẽ trả về một phản hồi trống.

>>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 2

Cách so sánh hai danh sách các đối tượng

Đôi khi chúng tôi có một danh sách các đối tượng tùy chỉnh mà chúng tôi muốn so sánh. Có thể chúng tôi muốn có được một khác biệt, hoặc chỉ kiểm tra xem chúng có chứa các yếu tố tương tự không. Giải pháp cho vấn đề này không thể khác: Sử dụng In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 2.

Ví dụ sau đây cho thấy sức mạnh của thư viện này. Chúng tôi sẽ so sánh hai danh sách có chứa một đối tượng tùy chỉnh và chúng tôi sẽ có thể khẳng định nếu chúng bằng hoặc không và sự khác biệt là gì.

Trong ví dụ dưới đây, chúng tôi có hai danh sách các đối tượng In [11]: numbers = [10, 30, 20] In [12]: target = [10, 20, 30] In [13]: DeepDiff(numbers, target) Out[13]: {'values_changed': {'root[1]': {'new_value': 20, 'old_value': 30}, 'root[2]': {'new_value': 30, 'old_value': 20}}} In [14]: DeepDiff(numbers, target, ignore_order=True) Out[14]: {} 6. Sự khác biệt duy nhất giữa hai là ở vị trí cuối cùng In [11]: numbers = [10, 30, 20] In [12]: target = [10, 20, 30] In [13]: DeepDiff(numbers, target) Out[13]: {'values_changed': {'root[1]': {'new_value': 20, 'old_value': 30}, 'root[2]': {'new_value': 30, 'old_value': 20}}} In [14]: DeepDiff(numbers, target, ignore_order=True) Out[14]: {} 6 đối tượng có một độ tuổi khác. In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 2 Không chỉ tìm thấy vị trí phù hợp - In [11]: numbers = [10, 30, 20] In [12]: target = [10, 20, 30] In [13]: DeepDiff(numbers, target) Out[13]: {'values_changed': {'root[1]': {'new_value': 20, 'old_value': 30}, 'root[2]': {'new_value': 30, 'old_value': 20}}} In [14]: DeepDiff(numbers, target, ignore_order=True) Out[14]: {} 9 - mà còn thấy rằng trường # Short list: compare_bitwise took 10.145 ms compare_listcomp took 11.157 ms compare_intersect took 7.461 ms # Long list: compare_bitwise took 11203.709 ms compare_listcomp took 17361.736 ms compare_intersect took 6833.768 ms 00 cũng khác nhau.

>>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 3

Cách so sánh hai danh sách các mảng Numpy

Trong phần này, chúng ta sẽ xem cách so sánh hai danh sách các mảng >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 9. Đây là một nhiệm vụ khá phổ biến đối với những người làm việc với khoa học dữ liệu và/hoặc học máy.

Chúng tôi đã thấy trong phần đầu tiên sử dụng toán tử >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 7 không hoạt động tốt với danh sách >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 9Arrays. May mắn thay, chúng ta có thể sử dụng ... đoán xem !? Có, chúng ta có thể sử dụng In [1]: import numpy as np In [2]: numbers = [np.ones(3), np.zeros(2)] In [3]: numbers Out[3]: [array([1., 1., 1.]), array([0., 0.])] In [4]: target = [np.ones(3), np.zeros(2)] In [5]: numbers == target --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b832db4b039d> in <module> ----> 1 numbers == target ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 2.

Ví dụ dưới đây cho thấy hai danh sách với các mảng >>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 9 khác nhau và thư viện có thể phát hiện vị trí chính xác mà chúng khác nhau. Thật tuyệt làm sao?

>>> numbers = [1, 2, 3] >>> target = [1, 2, 3] >>> numbers == target True >>> [1, 2, 3] == [1, 3, 2] False >>> ['name', 'lastname'] == ['name', 'lastname'] True >>> ['name', 'lastname'] == ['name', 'last name'] False 4

Sự kết luận

Trong bài đăng này, chúng tôi đã thấy nhiều cách để so sánh hai danh sách trong Python. Phương pháp tốt nhất phụ thuộc vào loại yếu tố chúng ta có và cách chúng ta muốn so sánh. Hy vọng, bây giờ bạn biết cách:

  • Kiểm tra xem hai danh sách có bằng Python không
  • So sánh hai danh sách không có thứ tự (danh sách không có thứ tự)
  • So sánh hai danh sách trong Python và các trận đấu trở lại
  • So sánh hai danh sách trong Python và sự khác biệt về trở lại
  • So sánh hai danh sách các chuỗi
  • So sánh hai danh sách từ điển
  • So sánh hai danh sách danh sách
  • So sánh hai danh sách các đối tượng
  • So sánh hai danh sách các mảng numpy

Bài viết khác mà bạn có thể thích:

  • Cách tốt nhất để so sánh hai từ điển trong Python

  • Cách so sánh hai chuỗi trong Python (theo 8 cách dễ dàng)

  • 7 cách khác nhau để làm phẳng danh sách các danh sách trong Python

Hẹn gặp lại bạn lần sau!

Bài đăng này ban đầu được xuất bản tại //miguendes.me

Làm cách nào để so sánh hai danh sách dữ liệu trong Python?

Phương thức python sort () và == Toán tử để so sánh các danh sách chúng ta có thể câu lạc bộ phương thức python sort () với toán tử == để so sánh hai danh sách. Phương thức python sort () được sử dụng để sắp xếp các danh sách đầu vào với mục đích nếu hai danh sách đầu vào bằng nhau, thì các phần tử sẽ nằm ở cùng một vị trí chỉ mục. to compare lists We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.

Làm thế nào để bạn so sánh hai danh sách?

Làm thế nào để so sánh hai danh sách trong Excel..
Chọn tất cả các ô trong cả hai danh sách ..
Trong menu của nhà trên mạng, chọn định dạng có điều kiện.
Chọn các quy tắc của các ô nổi bật trong menu này, theo sau là các giá trị trùng lặp.
Chọn trực tuyến độc đáo từ menu thả xuống đầu tiên, theo sau là định dạng ưa thích của bạn trong menu thứ hai ..

Làm thế nào để bạn so sánh hai danh sách có chứa chuỗi trong Python?

Có hai cách để thực hiện điều này: sắp xếp các danh sách và sử dụng toán tử ==.Chuyển đổi chúng thành đặt S và sử dụng toán tử ==.sorting the lists and using the == operator. converting them to set s and using the == operator.

Làm thế nào để bạn so sánh hai danh sách cho một vòng lặp trong Python?

Hàm SET () và toán tử ==..
list1 = [11, 12, 13, 14, 15].
list2 = [12, 13, 11, 15, 14].
a = set (list1).
B = Đặt (List2).
Nếu a == B:.
In ("List1 và List2 bằng nhau").
In ("List1 và List2 không bằng nhau").

Chủ đề