【问题标题】:Python splat/unpacking/* operator on sets: is the result always sorted?集合上的 Python splat/unpacking/* 运算符:结果是否总是排序的?
【发布时间】:2021-10-13 07:49:47
【问题描述】:

splat/unpacking 运算符 * 在应用于整数集时是否总是排序?

示例 1(整数):

In [1]: [*{8,3,6,3,2,1}]
Out[1]: [1, 2, 3, 6, 8]

计数器示例 2(字符串):

In [615]: [*{'b','d','a','c','e'}]
Out[615]: ['a', 'd', 'c', 'b', 'e']

反例 3(元组):

In [1]: [*{(2,3),(2,2),(1,2),(1,1)}]
Out[2]: [(2, 3), (1, 1), (1, 2), (2, 2)]

【问题讨论】:

    标签: python sorting integer operator-keyword splat


    【解决方案1】:

    不是的

    print([*{8,3,6,3,2,1,108,109,255,569}])
    

    给我:

    [1, 2, 3, 6, 8, 108, 109, 569, 255]
    

    您不能对集合进行排序。如果您需要对它们进行排序,则必须将它们转换为列表或使用特定模块,例如 sortedcontainers

    【讨论】:

    • 谢谢!很高兴知道。我想我没有尝试足够的例子。是的,我可以使用sorted(my_set) 进行排序。
    猜你喜欢
    • 2015-12-11
    • 2017-05-17
    • 2012-02-08
    • 2015-09-21
    • 1970-01-01
    • 2012-12-10
    • 2015-06-15
    • 2015-02-16
    • 1970-01-01
    相关资源
    最近更新 更多