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

2024-09-29 06:22:13 发布

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

您有两个数组(伪值),其中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")

在这个代码示例中,它为最大数组中的每个值打印出(示例)Device {'keyboard': '1'} is not in 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对象,我该如何处理呢


Tags: 对象in示例isdeviceexistsnotit
1条回答
网友
1楼 · 发布于 2024-09-29 06:22:13

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

>>> 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

相关问题 更多 >