“Python”比较两个列表并在列表包含“”时查找匹配项:(键值)

2024-09-30 16:23:29 发布

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

我正在寻找一种有效的方法来匹配两个列表中的哈希值,并打印出匹配的内容,以及与数据库对应的文件是什么?我完全没有主意了,有人能推荐一种方法来验证这些数据库吗?你知道吗

data_base=['9d377b10ce778c4938b3c7e2c63a229a : contraband_file1.jpg', '6bbaa34b19edd6c6fa06cccf29b33125 : contraband_file2.jpg', 'e4e7c3451a35944ca8697f9f2ac037f1 : contraband_file3.jpg', '1d6d9c72e3476d336e657b50a77aee05 : contraband_file4.gif']

hashed_files= ['6e3b028cc1972f6ad534b9fc1428eef6 : big.jpg', 'c9505a624181faa4be86cfe2af4b71eb : msc_asdf_logo.jpg', '6bbaa34b19edd6c6fa06cccf29b33125 : nothingtoseehere.docx', 'e4e7c3451a35944ca8697f9f2ac037f1 : StarWarsReview.docx', '0e89978428a4fe88fab1be364d998b57 : wargames.jpg']

Tags: 文件方法数据库内容列表databasefile1
2条回答

我将使用python列表和字典理解:

list_split1 = [s.split(' : ') for s in data_base]
list_split2 = [s.split(' : ') for s in hashed_files]
data_base_dict = {k:v for k,v in list_split1}
hashed_files_dict = {k:v for v,k in list_split2}
for f, h in hashed_files_dict.items(): #for python3.x  - for python2.x use .iteritems()
    if h in data_base_dict:
        print(f, data_base_dict[h])

这将导致:

StarWarsReview.docx contraband_file3.jpg
nothingtoseehere.docx contraband_file2.jpg

使用字典和列表迭代搜索:

data_base = {x.split(' : ')[0] : x.split(' : ')[1] for x in data_base}
hashed_files = {x.split(' : ')[1] : x.split(' : ')[0] for x in hashed_files}
matches = []
for file in hashed_files:
    if hashed_files[file] in data_base:
        matches.append((file, data_base[hashed_files[file]]))

结果与

>>> matches
[('StarWarsReview.docx', 'contraband_file3.jpg'), ('nothingtoseehere.docx', 'contraband_file2.jpg')]

相关问题 更多 >