如何检查字典列表是否已排序?
How to check if a list of dictionaries is sorted?
我创建了一个词典列表:
l = []
d = {"a":1,"b",2}
l.append(d)
d = {"a":5,"b":6}
l.append(d)
d = {"a":3,"b":4}
l.append(d)
现在,如何检查字典列表是否根据键 a
或键 b
排序?
只要使用默认检查是否排序,但比较前索引:
k = "a"
all(l[i][k] <= l[i+1][k] for i in range(len(l) - 1))
print(l == sorted(l, key=lambda d:d["a"]))
False
如 this answer 中所述,您可以使用以下方法有效地检查列表是否已排序:
all(l[i] <= l[i+1] for i in xrange(len(l)-1))
要支持自定义键,您可以定义类似
的内容
def is_sorted(iterable, key=None):
if key is None:
key = lambda x : x
return all(key(iterable[i]) <= key(iterable[i+1]) for i in xrange(len(iterable)-1))
在这种情况下,您可以只使用一个简单的 lambda 函数查找字典值作为键(假设所有元素都是包含 a
和 b
的字典),例如
# Check if list of dictionaries are sorted by value of 'a'
>>> is_sorted(l, key=lambda x: x["a"])
# Check if list of dictionaries are sorted by value of 'b'
>>> is_sorted(l, key=lambda x: x["b"])
# Check if list of dictionaries are sorted by value of 'a', then 'b'
>>> is_sorted(l, key=lambda x: (x["a"], x["b"]))
我创建了一个词典列表:
l = []
d = {"a":1,"b",2}
l.append(d)
d = {"a":5,"b":6}
l.append(d)
d = {"a":3,"b":4}
l.append(d)
现在,如何检查字典列表是否根据键 a
或键 b
排序?
只要使用默认检查是否排序,但比较前索引:
k = "a"
all(l[i][k] <= l[i+1][k] for i in range(len(l) - 1))
print(l == sorted(l, key=lambda d:d["a"]))
False
如 this answer 中所述,您可以使用以下方法有效地检查列表是否已排序:
all(l[i] <= l[i+1] for i in xrange(len(l)-1))
要支持自定义键,您可以定义类似
的内容def is_sorted(iterable, key=None):
if key is None:
key = lambda x : x
return all(key(iterable[i]) <= key(iterable[i+1]) for i in xrange(len(iterable)-1))
在这种情况下,您可以只使用一个简单的 lambda 函数查找字典值作为键(假设所有元素都是包含 a
和 b
的字典),例如
# Check if list of dictionaries are sorted by value of 'a'
>>> is_sorted(l, key=lambda x: x["a"])
# Check if list of dictionaries are sorted by value of 'b'
>>> is_sorted(l, key=lambda x: x["b"])
# Check if list of dictionaries are sorted by value of 'a', then 'b'
>>> is_sorted(l, key=lambda x: (x["a"], x["b"]))