【问题标题】:set to list conversion [duplicate]设置为列表转换[重复]
【发布时间】:2016-10-03 22:05:54
【问题描述】:

谁能给我解释一下原因:

p = {-1,2,-3}
print(p)

将打印

{2, -3, -1}

当我转换为列表时

pa = list(p)
print(pa)

我会得到

[2, -3, -1]

如何将 p 转换为具有相同项目顺序的列表

[-1, 2, -3]

PS:只有在我使用否定项时才会发生这种情况

【问题讨论】:

  • 套装未排序。一句话:除非您存储了订单,否则您无法保留订单...
  • 看似奇怪的事情发生在小整数周围,因为它们散列到自己的值,所以经常(但不总是)保持排序。但你不应该依赖字典或设置顺序。
  • 感谢您的及时回复。我已经知道集合是不可变的。但我别无选择。我从一种方法中得到了一套。我必须将其转换为列表(同时保持相同的顺序)才能将其提供给另一种方法。任何帮助!
  • 集合是不是不可变的。它们是无序的。没有顺序可守。

标签: python list python-3.x set


【解决方案1】:

set 在 python 中是无序的。如果您想保持元素的顺序,请改用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]

【讨论】:

  • 对不起,它不起作用,因为 fromkeys 不将集合作为参数
  • 您需要将初始化set的代码替换为collections.OrderedDict.fromkeys()。一旦创建了集合,就无法从中提取原始订单。
  • 我必须另辟蹊径。不过还是谢谢你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-16
  • 2013-05-07
  • 1970-01-01
  • 1970-01-01
  • 2021-06-09
  • 2021-09-08
相关资源
最近更新 更多