首页 > 解决方案 > 检查列表的每个字典中的参数值是否是顺序的

问题描述

我想检查当前是否id等于最后id+1,(这应该适用于列表中添加的任意数量的类似字典)

代码

listing = [
    {
        'id': 1,
        'stuff': "othervalues"
    },
    {
        'id': 2,
        'stuff': "othervalues"
    },
    {
        'id': 3,
        'stuff': "othervalues"
    }
]

for item in listing :
    if item[-1]['id'] == item['id']+1:
        print(True)

输出

Traceback (most recent call last):
  File "C:\Users\samuk\Desktop\Master\DV\t2\tester.py", line 10, in <module>
    if item[-1]['id'] == item['id']+1:
KeyError: -1

期望的结果

True

或者,如果失败,

False

标签: pythonlistdictionary

解决方案


要检查是否所有的ids 都在一个序列中,我们可以enumerate在这里使用。

def is_sequential(listing):
    start = listing[0]['id']
    for idx, item in enumerate(listing, start):
        if item['id'] != idx:
            return False
    return True

推荐阅读