gpt4 book ai didi

python - 为什么Python中排序列表转换为集合后元素顺序会发生变化?

转载 作者:行者123 更新时间:2023-12-01 00:07:48 24 4
gpt4 key购买 nike

为什么当我将列表转换为集合时顺序会发生变化?如何在 Python 中获得排序结果?

string = 'test'
result = sorted([character for character in string])
print(result)
#output
['e', 's', 't', 't']
print(set(result))
#output
{'t', 'e', 's'}

我正在尝试制作这个:

{'e', 's', 't'}

最佳答案

根据docs :

A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.

这里你应该使用:

from collections import OrderedDict
string = 'test'
result = sorted([character for character in string])
print(list(OrderedDict.fromkeys(result)))

或者,如果您的版本 >= 3.7,则字典已排序,因此您可以使用:

string = 'test'
result = sorted([character for character in string])
print(list(dict.fromkeys(result)))

关于python - 为什么Python中排序列表转换为集合后元素顺序会发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59833951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com