python - 检查列表的每个字典中的参数值是否是顺序的
问题描述
我想检查当前是否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
解决方案
要检查是否所有的id
s 都在一个序列中,我们可以enumerate
在这里使用。
def is_sequential(listing):
start = listing[0]['id']
for idx, item in enumerate(listing, start):
if item['id'] != idx:
return False
return True
推荐阅读
- c++-winrt - 如何从 C++/WinRT DateTime 创建一个 hstring?
- excel - 将用户名(数组)与电子邮件(数组)匹配
- subtyping - 如果 A 是 B 的子类型,那么 (A→B) → A 是否是 (B→B) → A 的子类型?
- python - 如何在 Kivy 中显示数独板?
- javascript - 编写一个函数来检测链表中的循环(弗洛伊德的算法)......逻辑看起来正确但找不到错误
- python - Pandas groupby 链接:将多索引列重命名为一行
- scala - Scala 如何允许使用类型参数而不是类型类进行覆盖
- sql - Running SSIS Solution/Package deletes components out of the Data Flow Task
- java - JSP 向 Angular 6+ UI 提供信息
- dart - 如何使用方法通道将任何 T 类型的列表从 Android 发送到 Flutter 端?