Python检查数组中的重复项

Python检查数组中的重复项,python,arrays,dictionary,Python,Arrays,Dictionary,我想检查myList中MyNewFile的内容。这是我的代码,但不会那么好 myList=[{"text": "1"},{"text": "2"},{"text": "3"},{"text": "4"},{"text": "5"},{"text": "6"}] myNewFile=[{"text": "10"},{"text": "5"},{"text": "7"},{"text": "8"}] for index in range(len(myNewFile)): if (myLis

我想检查myList中MyNewFile的内容。这是我的代码,但不会那么好

myList=[{"text": "1"},{"text": "2"},{"text": "3"},{"text": "4"},{"text": "5"},{"text": "6"}]
myNewFile=[{"text": "10"},{"text": "5"},{"text": "7"},{"text": "8"}]

for index in range(len(myNewFile)):
    if (myList[index]["text"]==myNewFile[index]["text"]):
        print "same"
    else:
        print "input"
最终结果:


它有一个相同的值(两个都有text=“5”)。有什么建议吗?谢谢

最简单的方法是将两个列表转换为集合,然后进行集合交集

  • 对于列表中的每个字典,获取
    items()
    列表,并将这些元素传递给
    set
    函数

    set1 = set(item for d in myList for item in d.items())
    set2 = set(item for d in myNewList for item in d.items())
    
  • 在这一点上,集合看起来像这样

    set([('text', '5'), ('text', '4'), ('text', '6'), ('text', '1'), ('text', '3'), ('text', '2')])
    set([('text', '7'), ('text', '10'), ('text', '5'), ('text', '8')])
    
    print {item[0]:item[1] for item in set1 & set2}
    # {'text': '5'}
    
  • 然后简单地使用
    &
    操作符进行交集,并使用字典理解重建原始字典,如下所示

    set([('text', '5'), ('text', '4'), ('text', '6'), ('text', '1'), ('text', '3'), ('text', '2')])
    set([('text', '7'), ('text', '10'), ('text', '5'), ('text', '8')])
    
    print {item[0]:item[1] for item in set1 & set2}
    # {'text': '5'}
    

  • 这是你的真实代码吗
    len(myFile)
    应该给您一个名称错误,因为
    myFile
    不存在。密钥是否总是相同的?您能否将值或项放入一个集合并使用集合操作?您的代码将检查具有相同索引的两个条目是否相同。如果myFile的长度太大,则会出现超出范围的问题。使用
    set1.intersection(set2)
    应该比
    &
    更具可读性。