将列表转换为一组更改元素顺序最近,我注意到当我转换一个list到set元素的顺序被更改,并按字符进行排序。考虑这个例子:x=[1,2,20,6,210]print x
# [1, 2, 20, 6, 210] # the order is same as initial orderset(x)# set([1, 2, 20, 210, 6]) # in the set(x) output order is sorted我的问题是-为什么会发生这种事?如何在不丢失初始订单的情况下设置操作(特别是设置差异)?
3 回答

牧羊人nacy
TA贡献1862条经验 获得超7个赞
A
set
是无序的数据结构。 不要使用 set
,但是 collections.OrderedDict
:>>> a = collections.OrderedDict.fromkeys([1, 2, 20, 6, 210])>>> b = collections.OrderedDict.fromkeys([6, 20, 1]) >>> collections.OrderedDict.fromkeys(x for x in a if x not in b)OrderedDict([(2, None), (210, None)])
注意…的顺序 b
不重要,所以它可以是任何可迭代的,但它应该是一个可迭代的,支持O(1)成员资格测试。
编辑
>>> a = [1, 2, 20, 6, 210]>>> b = set([6, 20, 1])>>> [x for x in a if x not in b][2, 210]
b
a
collections.OrderedDict
.

慕勒3428872
TA贡献1848条经验 获得超6个赞
>>> x = [1, 2, 20, 6, 210]>>> sorted(set(x), key=x.index)[1, 2, 20, 6, 210]

有只小跳蛙
TA贡献1824条经验 获得超8个赞
添加回答
举报
0/150
提交
取消