如何使用Python使用sqlite3查找元组中的重复项?

2024-09-30 01:24:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉Python,但我喜欢这门语言!在

我有一个巨大的sqlite3数据库,其中包含row 0中文件的路径,以及{}中的文件{}。在

我需要根据它们的MD5搜索重复文件,我想将这些重复文件组织为dictionaries,如下所示:

{"b23e5d453643f66b68634d0204884cdf":an array of all paths that have the same MD5, like the one that is the key of this dictionary}

我使用以下代码搜索数据库并生成tuples

^{pr2}$

结果如下:

[[u'b23e5d453643f66b68634d0204884cdf'], [u'/Volumes/Backup/images_to_test/File_one_copy.png']]
[[u'b23e5d453643f66b68634d0204884cdf'], [u'/Volumes/Backup/images_to_test/File_one.png']]
[[u'f0b4108172c50f243d9e0132df4703a0'], [u'/Volumes/Backup/images_to_test/File_with_no_duplicate.png']]

我尝试过的每一个可能的解决方案都非常充分,而且性能非常糟糕。最好的Python方法是什么?在

谢谢你!在


Tags: 文件ofthetotest数据库thatpng
3条回答

如果我没听错,你想要这样的东西:

{u'b23e5d453643f66b68634d0204884cdf':
     [u'/Volumes/Backup/images_to_test/File_one_copy.png', u'/Volumes/Backup/images_to_test/File_one.png'],
 u'f0b4108172c50f243d9e0132df4703a0':
     [u'/Volumes/Backup/images_to_test/File_with_no_duplicate.png']
}

这非常适合defaultdict(从Python2.5开始提供)

^{pr2}$

如果要按MD5组合,则首先要按MD5对列表进行排序。在您的例子中,这最好留给sqlite,因此您应该在查询中添加orderby(参见https://mariadb.com/kb/en/order-by-clause/)。之后,您应该遍历所有行并按照以下行执行操作:

if currentMD5 != previousMD5:
  dictionary[currentMD5] = [currentFilePath]
else:
  dictionary[currentMD5].append(currentFilePath]
currentMD5 = previousMD5

您可以将cur放入一个循环中,只检索实际使用的列,并在循环中使用元组解包,如下所示:

db = sqlite3.connect('imges.db')
with db:
    cur = db.cursor()    
    cur.execute("SELECT row1, row3 FROM IMAGES")

    for row1, row3 in cur:
        print [[row3],[row1]]

另外,为什么不使用DISTINCT?在

^{pr2}$

相关问题 更多 >

    热门问题