【问题标题】:Python check a list of dict if it is in correct order or got extra dictPython 检查 dict 列表是否顺序正确或有额外的 dict
【发布时间】:2021-10-18 07:16:40
【问题描述】:
a=[{'post':'up', 'address':1, 'index':96},
   {'post':'up', 'address':1, 'index':97},
   {'post':'up', 'address':1, 'index':98},
   {'post':'down', 'address':1, 'index':96},
   {'post':'down', 'address':1, 'index':98},
   {'post':'down', 'address':1, 'index':97},
   {'post':'down', 'address':1, 'index':99}]

这是我需要检查上/下对的字典列表。

  1. 每次向上,都会有一个具有相同地址和索引的向下。
  2. down dict 的 order 需要遵循 up dict 的顺序 - 遵循 index 的顺序 (up index:96,97,98 同时 down index: 96,98,97,99 )

这里是我写的。它会检查帖子——如果它是up,它会放入一个list_up,然后与down的地址和索引进行比较。如果正确,就会弹出list_up。

接下来,它会检查 list_up 的长度,以确定是否有额外的下降

list_up=[]
for item in a:
    if item['post'] == 'up':
        list_up.append(item)
    else:
        print('1 >>', list_up[0]) #for debug purpose
        print('2 >>', item) #for debug purpose
        if list_up[0]['address'] != item['address'] or list_up[0]['index'] != item['index'] :
            # print(queue_in_cmd[0])
            print(item)

        else:
            list_up.pop()
            print(True) #for debug purpose

if len(list_up) == 0:
    print('got extra down post')

以下是我的输出,其循环顺序不正确。

1 >> {'post': 'up', 'address': 1, 'index': 96}
2 >> {'post': 'down', 'address': 1, 'index': 96}
True
1 >> {'post': 'up', 'address': 1, 'index': 96}
2 >> {'post': 'down', 'address': 1, 'index': 98}
{'post': 'down', 'address': 1, 'index': 98}
1 >> {'post': 'up', 'address': 1, 'index': 96}
2 >> {'post': 'down', 'address': 1, 'index': 97}
{'post': 'down', 'address': 1, 'index': 97}
1 >> {'post': 'up', 'address': 1, 'index': 96}
2 >> {'post': 'down', 'address': 1, 'index': 99}
{'post': 'down', 'address': 1, 'index': 99}

我想要的输出是使代码仅返回 {'post': 'down', 'address': 1, 'index': 98} 因为向下字典具有出现的索引早于它应该出现的时间。并且还返回got extra down post,因为它有额外的down

p/s:抱歉我的描述太混乱了。

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
  • @timgeb 我已经输入了我想要的输出并修改了我的描述。希望不要混淆

标签: python loops dictionary


【解决方案1】:

也许这会有所帮助:

a = [{'post': 'up', 'address': 1, 'index': 96},
     {'post': 'up', 'address': 1, 'index': 97},
     {'post': 'up', 'address': 1, 'index': 98},
     {'post': 'down', 'address': 1, 'index': 96},
     {'post': 'down', 'address': 1, 'index': 98},
     {'post': 'down', 'address': 1, 'index': 97},
     {'post': 'down', 'address': 1, 'index': 99}]
u = []
d = []
for _a in a:
    (_ := u if _a['post'] == 'up' else d).append(_a['index'])

if u == d:
    print('Everything looks good')
elif len(u) == len(d):
    print('Out of order')
elif len(u) > len(d):
    print('Too many up')
else:
    print('Too many down')

【讨论】:

  • 嗨@BrutusForcus。我似乎无法理解这一行 (_ := u if _a['post'] == 'up' else d).append(_a['index'])
  • 这利用了 Python 3.8+ 中提供的所谓“海象运算符”
猜你喜欢
  • 2013-12-30
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 2022-09-25
  • 1970-01-01
相关资源
最近更新 更多