taizilongxu / interview_python

关于Python的面试题
16.63k stars 5.55k forks source link

5 去除列表中的重复元素 # 用字典并保持顺序 #45

Open coder1688 opened 6 years ago

coder1688 commented 6 years ago

用字典并保持顺序

l1 = ['b','c','d','b','c','a','a'] l2 = list(set(l1)) //应改成 l2={}.fromkeys(l1).keys() l2.sort(key=l1.index) print l2

pusidun commented 6 years ago
>>> l1=['b','c','d','c','a','a']
>>> l2=list(set(l1))
>>> l2.sort(key=l1.index)
>>> print(l2)
['b', 'c', 'd', 'a']

我在python3上运行没有问题