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

标签 python list python-2.7 dictionary compare

我正在尝试创建用于比较两个列表中的项目的函数,如果列表中的字符串甚至部分匹配,则编写类似 {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/

相关文章:

python - 将今天的日期与sqlite数据库表中的日期字段进行比较

python - 为什么 Windows 上的 python 2.7 在打印时需要在 unicode 字符前加一个空格?

python - 使用 Numpy 创建勒让德公式

python - 在 Python 脚本中隐藏登录凭据

python - Python 中带有子进程的 Shell 管道

c# - 将 SQL 表读入 Dictionary<string, List<string[]>>

c# - 在列表中保存带有参数的方法调用并执行它们

python - Pandas 列差异,包含列表

python - 可以从现有日期时间实例创建的自定义日期时间子类?

python - 在 Python 2.7 中隐藏导出列表中的名称