【发布时间】: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}]
这是我需要检查上/下对的字典列表。
- 每次向上,都会有一个具有相同地址和索引的向下。
- 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