我有像这样的字典
{'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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句