gpt4 book ai didi

python - 字典中两个列表结果的比较具有重复的项目

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:53 25 4
gpt4 key购买 nike

我正在尝试创建用于比较两个列表中的项目的函数,如果列表中的字符串甚至部分匹配,则编写类似 {item_list1_as_key:item_list2_as_value} 的结果。这个函数看起来像:

def compareItemsInLists(ref, searchlist):
matchdict=dict.fromkeys(ref, [])
for item in ref:
for stitem in searchlist:
if item in stitem:
print "Key %s matches string %s" %(item,stitem)
matchdict[item].append(stitem)
return matchdict

ref=["a","b","c"]
searchlist=["aaa","bab","cbc","ddd"]

但是,我得到了这样的返回:

Key a matches string aaa
Key a matches string bab
Key b matches string bab
Key b matches string cbc
Key c matches string cbc
{'a': ['aaa', 'bab', 'bab', 'cbc', 'cbc'],
'c': ['aaa', 'bab', 'bab', 'cbc', 'cbc'],
'b': ['aaa', 'bab', 'bab', 'cbc', 'cbc']}

看起来比较效果很好,但我无法发现 .append 函数出了什么问题。为什么它会在 searchlist 中写入重复的项目和不匹配的项目?

最佳答案

看起来 matchdict=dict.fromkeys(ref, []) 行对每个键使用相同列表的引用。如 this answer 中所述,您可以使用这样的字典理解:

matchdict={key: list() for key in ref}

关于python - 字典中两个列表结果的比较具有重复的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29109355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com