在Python中与字符串列表比较时无法找到唯一的值



我有两个数据库,每个包含309 (old_root)和483(根)表。我使用我编写的函数table_search()提取了两个包含两个数据库所有表的名称的列表,该函数返回一个布尔标志值(这是无关的),并提取了一个包含数据库所有表的列表,该列表在下面的代码片段中被调用。该函数工作完美,列表包含两个数据库的所有表的名称。

unique_d1_tables = []
unique_d2_tables = []
d1_tables = []
d2_tables = []
unique_total_tables = []
temp_d1 = []
f, tab_list = table_search("old_root", "x")
d1_tables = tab_list
temp_d1=tab_list
print("Total number of tables in old_root:", len(d1_tables))

f, tab_list = table_search("root", "x")
unique_total_tables = d1_tables
d2_tables = tab_list
print("Total number of tables in root:", len(tab_list))
print("Total number of tables in both old_root & root (including duplicates):", len(d1_tables + d2_tables))
unique_total_tables.extend(x for x in tab_list if x not in unique_total_tables)
print("Total number of tables in both old_root & root (excluding duplicates):", len(unique_total_tables))
unique_d1_tables.extend(x for x in d1_tables if x not in d2_tables)
print("Total number of tables in old_root not present in root:", len(unique_d1_tables))
unique_d2_tables.extend(x for x in d2_tables if x not in d1_tables)
print("Total number of tables in root not present in old_root:", len(unique_d2_tables))

除了最后一种情况外,该代码段工作得很好,在这种情况下,要找到D2(根)的唯一表。输出:

Total number of tables in old_root: 309
Total number of tables in root: 483
Total number of tables in both old_root & root (including duplicates): 792
Total number of tables in both old_root & root (excluding duplicates): 484
Total number of tables in old_root not present in root: 1
Total number of tables in root not present in old_root: 0

最后一行的值应该是175。Unique_d2_tables也是一个空列表。我用较小的虚拟数据库检查了输出,每个数据库包含2个和3个表,最后一个案例再次失败。请让我知道我的代码中的缺陷,因为有些东西没有被正确考虑。

unique_total_tables = d1_tables通过引用传递列表d1_tables。这意味着当您扩展unique_total_tables时,您实际上是在扩展d1_tables

你可以通过复制列表来修复这个问题。

使用unique_total_tables = d1_tables[:]。这相当于unique_total_tables = [x for x in d1_tables]

最新更新