我有一本像这样的字典
{'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'
和 '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])))
我认为,这远不是更改值的最有效方法,而且它不适用于无序字典。如何有效地做到这一点?如果字典未排序,是否有任何方法可以轻松地重新分配值?
最佳答案
将字典转换为排序列表,然后构建一个没有要删除的单词的新字典:
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
.
关于python - 重新分配字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50665866/