首页 > 解决方案 > 为什么我不能将我的列表(应用了一些函数)转换为 python 中的集合

问题描述

我有一个列表,其中存储了一些元素。我想对列表的所有元素应用 ssome 函数,并希望将列表排序为相反的顺序。然后我想将结果列表转换为set(). 但是我的代码似乎不起作用。有人可以看看并告诉我我的代码有什么问题。最后一行是 print a 的输出。这段代码有什么问题

B=[2,3,4,5,7,66,56,34,22,345, 22,3,5]
a=set(sorted([2*t for t in B], reverse=True))
print(a)
# output: {132, 68, 6, 4, 8, 10, 44, 14, 112, 690}

现在以其他形式,我的代码是:

sorted(set([2*t for t in B]), reverse=True)

这似乎工作正常并产生:

[690, 132, 112, 68, 44, 14, 10, 8, 6, 4]

有人能说出区别吗

标签: pythonpython-3.xcollectionslist-comprehension

解决方案


Set对象不保留顺序,因为它们使用哈希表来保留它们的项目。相反,您可以使用它OrderedDict.fromkeys来获取可迭代的唯一且有序的表示。

In [6]: sorted_b = sorted([2*t for t in B], reverse=True)

In [7]: from collections import OrderedDict

In [8]: OrderedDict.fromkeys(sorted_b)
Out[8]: 
OrderedDict([(690, None),
             (132, None),
             (112, None),
             (68, None),
             (44, None),
             (14, None),
             (10, None),
             (8, None),
             (6, None),
             (4, None)])

推荐阅读