python-3.x 如何独立于位置使用difflib?

1qczuiv0  于 2022-12-15  发布在  Python
关注(0)|答案(2)|浏览(115)

我有这样一个代码

import difflib

list1 = ["ameixa","bolo","guarana","caju","pizza","maracuja","forro", "coco"]
list2 = ["ameixa","guarana","caju","pizza","maracuja","forro","bolo"]

for line in difflib.unified_diff(list1, list2, fromfile='file1', tofile="file2", lineterm=""):
    print(line)

字符串
问题是:正在返回:

--- file1
+++ file2
@@ -1,8 +1,7 @@
 ameixa
-bolo
 guarana
 caju
 pizza
 maracuja
 forro
-coco
+bolo

所以,正如你所看到的,“博洛”在两个列表中都有,但是它在两个列表中被识别为不同的元素,我怎么能在不考虑位置的情况下比较它们呢?

r1zk6ea1

r1zk6ea11#

我建议将这两个列表转换为sets,然后再转换为list

list1 = list(set(list1))
list2 = list(set(list2))

输出1

>>> print(list1)
... ['caju', 'forro', 'coco', 'ameixa', 'pizza', 'maracuja', 'bolo', 'guarana']
>>> print(list2)
... ['caju', 'forro', 'ameixa', 'pizza', 'maracuja', 'bolo', 'guarana']

当我们应用脚本时,我们得到:

for line in difflib.unified_diff(list1, list2, fromfile='file1', tofile="file2", lineterm=""):
    print(line)

产出2

--- file1
+++ file2
@@ -1,6 +1,5 @@
 caju
 forro
-coco
 ameixa
 pizza
 maracuja
k97glaaz

k97glaaz2#

在运行difflib.unified_diff之前对列表进行排序。

for line in difflib.unified_diff(sorted(list1), sorted(list2), fromfile='file1', tofile="file2", lineterm=""):
    print(line)

输出:

--- file1
+++ file2
@@ -1,7 +1,6 @@
 ameixa
 bolo
 caju
-coco
 forro
 guarana
 maracuja

编辑:

这是一个不使用difflib.unified_diff的解决方案,这可能更简单。从问题是不那么清楚什么是你想要的输出,虽然:

# Find elements in list1 that are missing in list2
one_not_two = set(list1).difference(list2)
# Find elements in list2 that are missing in list1
two_not_one = set(list2).difference(list1)
# Find elements in common
one_and_two = set(list1).intersection(list2)

相关问题