任何人都可以向我解释原因:
p = {-1,2,-3}
print(p)
将打印
{2, -3, -1}
当我转换为列表
pa = list(p)
print(pa)
我会得到
[2, -3, -1]
如何将p转换为具有相同项目顺序的列表
[-1, 2, -3]
PS:只有当我使用负面物品
时才会发生这种情况答案 0 :(得分:0)
set
是无序的。如果您想维护元素的顺序,请改用collections.OrderedDict.fromkeys()
。这也将表现为set
。例如:
>>> import collections
>>> p = collections.OrderedDict.fromkeys([-1,2,-3])
>>> print(p)
OrderedDict([(-1, None), (2, None), (-3, None)])
>>> p = collections.OrderedDict.fromkeys([-1,2,-3,2]) # <-- 2 repeated twice
>>> print(p) # <-- Removed duplicated entry of '2', same as set
OrderedDict([(-1, None), (2, None), (-3, None)])
>>> l = list(p)
>>> print(l) # <-- order is maintained
[-1, 2, -3]