python - 重新分配字典值
问题描述
我有一本像
{'A': 0, 'B': 1, 'C': 2, 'D': 3, etc}
如果字典未排序,如何从该字典中删除元素而不产生值间隙?
一个例子:
我有一个大矩阵,其中行代表单词,列代表遇到这些单词的文档。我将单词及其相应的索引存储为字典。例如对于这个矩阵
2 0 0
1 0 3
0 5 1
4 1 2
字典看起来像:
words = {'apple': 0, 'orange': 1, 'banana': 2, 'pear': 3}
如果我删除单词'apple'
and 'banana'
,矩阵将只包含两行。所以'orange'
字典中的值现在应该等于0
而不是1
,的值'pear'
应该是1
而不是3
。
在 Python 3.6+ 中,字典是有序的,所以我可以写这样的东西来重新分配值:
i = 0
for k, v in words.items():
v = i
i += 1
或者,或者,
words = dict(zip(terms.keys(), range(0, matrix.shape[0])))
我认为,这远不是更改值的最有效方法,而且它不适用于无序字典。如何有效地做到这一点?如果字典没有排序,有什么方法可以轻松地重新分配值?
解决方案
将 dict 转换为排序列表,然后构建一个没有要删除的单词的新 dict:
import itertools
to_remove = {'apple', 'banana'}
# Step 1: sort the words
ordered_words = [None] * len(words)
for word, index in words.items():
ordered_words[index] = word
# ordered_words: ['apple', 'orange', 'banana', 'pear']
# Step 2: Remove unwanted words and create a new dict
counter = itertools.count()
words = {word: next(counter) for word in ordered_words if word not in to_remove}
# result: {'orange': 0, 'pear': 1}
这具有 O(n) 的运行时间,因为使用索引操作手动排序列表是线性操作,而不是sorted
O(n log n)。
另请参阅itertools.count
和的文档next
。
推荐阅读
- r - R如何对我的数据列中的每个唯一因素循环多个计算并将每个计算附加到新列或表中
- html - 引导程序仅在一页中不对齐
- python - 一些 for 循环数在迭代列表时应该增加时减少
- sql - Teradata 中的 IF ELSE 语句
- hibernate - 带有额外列的 JPA @Many-To-Many 和 @OrderColumn 删除不会更新 @OrderColumn 值
- azure-sql-database - 将弹性池中的所有数据库添加到可用性组
- twilio - TwiML Sip 只拨第一个
- nginx - Nginx 代理传递给 s3 以获取 js 文件返回 400 Bad request
- c - 测量 n 个进程的时间
- reactjs - 为什么我的绑定在构造函数中不起作用