python - 为什么我不能将我的列表(应用了一些函数)转换为 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]
有人能说出区别吗
解决方案
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)])
推荐阅读
- c - C用fork()编写后关闭FDT?
- php - 基于另一个表日期的表中数据的总和(成本)
- python - Python脚本无法访问存储服务器
- google-chrome - Chrome 90 在 CORS 预检中向 Angular localhost 应用添加 https
- salesforce - Salesforce B2B Commerce/Cloudcraze,如何按产品名称对产品列表搜索结果进行排名
- vercel - Vercel 旧预览部署
- php - apache php windows 优势数据库重新连接问题
- swift - 是否可以将自定义工具添加到 PKToolPicker?
- function - 一个函数中有两个“scrollIntoView”
- sed - 使用 sed 删除目录中多个文件上的一些文本