我有一个已经按密钥id排序的字典列表。
y = [{'id': 0, 'name': 'Frank'}, {'id': 5, 'name': 'Hank'}, {'id': 8, 'name': 'Fred'}, {'id': 30, 'name': 'Jill'}]我想在列表中插入一个新元素。
y.append({'id': 6, 'name': 'Jenkins'})添加新元素后,如何避免再次按如下方式对列表进行排序?
y = sorted(y, key=lambda x: x['id'])理想的结果是:
y = [{'id': 0, 'name': 'Frank'}, {'id': 5, 'name': 'Hank'}, {'id': 6, 'name': 'Jenkins'}, {'id': 8, 'name': 'Fred'}, {'id': 30, 'name': 'Jill'}]编辑:
使用bisect.insort(y, {'id': 6, 'name': 'Jenkins'})仅适用于第一个键,如果dict按名称排序,则会失败。
I've got a list of dictionaries that is already sorted by a key id.
y = [{'id': 0, 'name': 'Frank'}, {'id': 5, 'name': 'Hank'}, {'id': 8, 'name': 'Fred'}, {'id': 30, 'name': 'Jill'}]I want to insert a new element into the list.
y.append({'id': 6, 'name': 'Jenkins'})How do I avoid sorting the list again as follows once the new element is added?
y = sorted(y, key=lambda x: x['id'])The ideal outcome is:
y = [{'id': 0, 'name': 'Frank'}, {'id': 5, 'name': 'Hank'}, {'id': 6, 'name': 'Jenkins'}, {'id': 8, 'name': 'Fred'}, {'id': 30, 'name': 'Jill'}]Edit:
Using bisect.insort(y, {'id': 6, 'name': 'Jenkins'}) will work only for the first key, if the dict is sorted by name, it will fail.
最满意答案
由于列表中的插入无论如何都在O(n)中 ,任何聪明的bisect算法都没有那么有用,因此您可以简单地循环列表以找到应该插入的位置,然后插入它。 就像是:
new_value = {'id': 6, 'name': 'Jenkins'} for index, value in enumerate(y): # Assuming y is in increasing order. if value['id'] > new_value['id']: y.insert(index, new_value) breakSince a insertion in a list is in O(n) anyway, any clever bisect algorithm is not that useful, so you can simply loop the list to find the position where it should be inserted, and then insert it. Something like:
new_value = {'id': 6, 'name': 'Jenkins'} for index, value in enumerate(y): # Assuming y is in increasing order. if value['id'] > new_value['id']: y.insert(index, new_value) break更多推荐
发布评论