Python:将新元素插入到排序的字典列表中(Python: insert new element into sorted list of dictionaries)

编程入门 行业动态 更新时间:2024-10-23 22:22:14
Python:将新元素插入到排序的字典列表中(Python: insert new element into sorted list of dictionaries)

我有一个已经按密钥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) break

Since 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

更多推荐

本文发布于:2023-08-04 10:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1414824.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   新元素   列表中   Python   insert

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!