如何比较2个不同长度的json-list?

时间:2019-04-26 09:08:33

标签: python while-loop

我得到了两个不同长度的JSON回复:“ data”和“ data_out”。

“数据”的短部分:

DATABASES = {
   'default': {
       'ENGINE': 'django.db.backends.sqlite3',
       'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
   }
}

然后,该块可以在“数据”中随机重复。 “ data_out”中相同,但是还有其他日期/时间。

我需要制作一个文件,其中两个JSON列表将按日期和时间排序。 我用“ while”来做。

    "value":[
    {
    "A": "1112233"
    "B": "Abcdef"
    "C": "2019-04-26T10:00:00"
    "D": "http://aol.com/aaaa.mp3"
    "E": "880020030000"
    }
    ]

但是我有一个问题,即“数据”比“ data_out”更早结束。有时候是这样,但是有时候“ data_out”比“ data”长,我有错误:

index_3 = 0
index_out_3 = 0
while index_3 < len(data['value']):
    while index_out_3 < len(data_out['value']):
        time_in = (data['value'][index_3]['C'])
        time_out = (data_out['value'][index_out_3]['C'])

        if time_in < time_out:
            #<put all info from 'data' to xls-file>
            index_3 += 1
        else:
            #<put all info from 'data_out' to xls-file>
            index_out_3 += 1

3 个答案:

答案 0 :(得分:0)

如果您要使用两个单独的索引变量,我认为您实际上不需要两个while循环。

while index_3 < len(data['value']) and index_out_3 < len(data_out['value']):
    time_in = (data['value'][index_3]['C'])
    time_out = (data_out['value'][index_out_3]['C'])
    if time_in < time_out:
        <put all info from 'data' to xls-file>
        index_3 += 1
    else:
        <put all info from 'data_out' to xls-file>
        index_out_3 += 1

这可以确保您的代码在任何JSON列表到达末尾时都将退出。 如果要在退出后进行其他工作,请考虑循环内部或外部的其他情况。

答案 1 :(得分:0)

如果datadata_out具有类似的结构(如您的示例), 您可以将两个列表链接在一起,然后按时间排序。

from itertools import chain

# chain lists together, e.g. chain([2, 1], [4, 3]) => iterable(2, 1, 4, 3)
result = chain(data["value"], data_out["value"])
result = sorted(result, key=lambda d: d["C"])
# <put all info from 'result' to xls-file>

答案 2 :(得分:0)

https://github.com/xlwings/jsondiff太酷了,我非常依赖它。感谢这个软件包的创建者

这是代码首页自述文件的纯摘录

  
    
      

从jsondiff导入差异

             

diff({'a':1,'b':2},{'b':3,'c':4})

    
  

{'c':4,'b':3,删除:['a']}

  
    
      

diff(['a','b','c'],['a','b','c','d'])

    
  

{插入:[(3,'d')]}

相关问题