如果在JSON中重复一次不止一次,该如何删除值?
我有一个类似于下面的JSON,
a = {"infinity_war":["Stark", "Hulk", "Rogers", "Thanos"],
"end_game":["Stark", "Dr.Strange", "Peter"]}
因为“ Stark”这个名字在整个JSON中重复一次不止一次,我只需要保留一个“ stark”并删除其他出现。我尝试使用熊猫,但需要所有长度的列表。还有其他方法吗?我需要的结果是
a = {"infinity_war":["Stark", "Hulk", "Rogers", "Thanos"],
"end_game":["Dr.Strange", "Peter"]}
I have a json like below
a = {"infinity_war":["Stark", "Hulk", "Rogers", "Thanos"],
"end_game":["Stark", "Dr.Strange", "Peter"]}
Since the name "Stark" is repeating more than once in the whole json I need to keep only one occurrence of "Stark" and remove the others. I tried using pandas but it needs all the list with same length. Is there any other way. The result I need is
a = {"infinity_war":["Stark", "Hulk", "Rogers", "Thanos"],
"end_game":["Dr.Strange", "Peter"]}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用简单的循环和一个集合来跟踪可见元素:
输出:
如何工作:
对于每个键/列表对,迭代列表的元素。如果在看到的集合中找到一个元素,请跳过将其添加到新列表中,否则将其附加到可见的集合中,然后将其添加到新列表中。
sead.Add(x)
始终为false asset.Add
返回无,因此(x in Sew.add(x))
>在SEED 中具有x的布尔值,我们将其反向
而不是
。You can use a simple loop and a set to keep track of the seen elements:
output:
How it works:
for each key/list pair, iterate over the elements of the list. If an element is found in the seen set, skip adding it to the new list, else append it to the seen set and add it to the new list.
seen.add(x)
is always False asset.add
returns None, so(x in seen or seen.add(x))
has the boolean value ofx in seen
, which we invert withnot
.