解决python字典(Dict)和集合(Set)的无序问题
python中的数据结构Dict和Set使用hash存储,无法按有序状态遍历。可以使用OrderedDict使字典变为有序,用sort方法使set还原顺序。
一、OrderedDict
python3.6之后,可以通过from collections import OrderedDict,使用有序字典。此时字典将按照元素插入的顺序输出。
from collections import OrderedDict W = OrderedDict() # 有序字典 W.['a'] = 1 W.['b'] = 2 W.['c'] = 3 # or W = OrderedDict({'a': 1, 'b': 2, 'c': 3})
print(W.keys()) for w in W.values(): print(w) #输出 Odict.keys(['a', 'b', 'c']) Odict.values([1, 2, 3])
二、Set
当无需去重操作时,可以使用列表代替集合。
需要去重时,可以在set操作后为结果按照原顺序重新排序。
words_char = ['a','a','e','c','a','d','d','c','b'] words = list(set(words_char)) # 去重 set后词语顺序随机 words.sort(key = words_char.index) # 将元素顺序变为原始顺序 print(words) #输出 ['a','e','c','d','b']