Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将两个数组与JSON对象作为项目进行比较的最佳方法_Python_Arrays_Json_Python 3.x - Fatal编程技术网

在python中将两个数组与JSON对象作为项目进行比较的最佳方法

在python中将两个数组与JSON对象作为项目进行比较的最佳方法,python,arrays,json,python-3.x,Python,Arrays,Json,Python 3.x,您有两个数组(伪值),其中JSON对象作为数组中的每个项: ArrayOne: [{'keyboards':'1'},{'keyboards':'2'},{'keyboards':'3'},{'mice':'1'}] 阵列2: [{'keyboards':'1'},{'keyboards':'2'},{'mice':'1'}] 我想同时循环遍历每个数组,如果arrayOne中有一个值存在于arrayTwo中,但不存在于arrayTwo中,则将其标记(做点什么) 这是我的代码示例: for dev

您有两个数组(伪值),其中JSON对象作为数组中的每个项:

ArrayOne:

[{'keyboards':'1'},{'keyboards':'2'},{'keyboards':'3'},{'mice':'1'}]

阵列2:

[{'keyboards':'1'},{'keyboards':'2'},{'mice':'1'}]

我想同时循环遍历每个数组,如果arrayOne中有一个值存在于arrayTwo中,但不存在于arrayTwo中,则将其标记(做点什么)

这是我的代码示例:

for deviceAndID in ArrayOne:
        if deviceAndID in ArrayTwo:
             print("It exists in both arrays")
        else:
             print("Device " + str(deviceAndID) + "is not in arrayTwo")
在这个代码示例中,它打印出(一个示例)
设备{'keyboard':'1'}不在arrayTwo
的最大数组中的每个值

实际上,我需要它根据上面的两个数组打印出以下内容:

It exists in both arrays
It exists in both arrays
Device {'keyboard': '3'} is not in arrayTwo
It exists in both arrays

我觉得这个问题是由每个元素或项都是json对象这一事实引起的,那么考虑到它们是列表中的json对象,我该如何处理呢

>>> ArrayOne = [{'keyboards': '1'}, {'keyboards': '2'}, {'keyboards': '3'}, {'mice': '1'}]
>>> ArrayTwo = [{'keyboards': '1'}, {'keyboards': '2'}, {'mice': '1'}]
>>> for deviceAndID in ArrayOne:
        if deviceAndID in ArrayTwo:
             print("It exists in both arrays")
        else:
             print("Device " + str(deviceAndID) + "is not in arrayTwo")

             
It exists in both arrays
It exists in both arrays
Device {'keyboards': '3'}is not in arrayTwo
It exists in both arrays

这是我根据你的问题得出的结论:

>>> ArrayOne = [{'keyboards': '1'}, {'keyboards': '2'}, {'keyboards': '3'}, {'mice': '1'}]
>>> ArrayTwo = [{'keyboards': '1'}, {'keyboards': '2'}, {'mice': '1'}]
>>> for deviceAndID in ArrayOne:
        if deviceAndID in ArrayTwo:
             print("It exists in both arrays")
        else:
             print("Device " + str(deviceAndID) + "is not in arrayTwo")

             
It exists in both arrays
It exists in both arrays
Device {'keyboards': '3'}is not in arrayTwo
It exists in both arrays

你面临的问题是什么?我运行了你的代码,结果就是你在问题底部包含的代码。@AmirAfianian真的吗??对我来说并没有,我只是复制粘贴了?是的,我要发布我的内容results@AmirAfianian谢谢,也许可以把它加到我问题的末尾?这真的很奇怪吗?@Nathan,我也测试过了,效果和你的输出完全一样。你面临的问题是什么?我运行了你的代码,结果就是你在问题底部包含的代码。@AmirAfianian真的吗??对我来说并没有,我只是复制粘贴了?是的,我要发布我的内容results@AmirAfianian谢谢,也许可以把它加到我问题的末尾?这真的很奇怪吗?@Nathan,我也测试过了,效果和你的输出完全一样