首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >比较两个数组和JSON对象作为python中的项的最佳方法

比较两个数组和JSON对象作为python中的项的最佳方法
EN

Stack Overflow用户
提问于 2020-10-30 03:23:13
回答 1查看 232关注 0票数 0

您有两个数组(虚拟值),数组中的每个项目都包含JSON对象:

ArrayOne:

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

ArrayTwo:

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

我希望同时遍历每个数组,如果arrayOne中的值在arrayTwo中存在,但在arrayTwo中不存在,则将其标记出来(做点什么)。

这是我的代码示例:

代码语言:javascript
复制
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

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

代码语言:javascript
复制
It exists in both arrays
It exists in both arrays
Device {'keyboard': '3'} is not in arrayTwo
It exists in both arrays

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-30 03:33:32

这是我根据你的问题得到的:

代码语言:javascript
复制
>>> 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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64597899

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档