【问题标题】:Inconsistency of converting list to set in python-3在 python-3 中将列表转换为设置的不一致
【发布时间】:2021-12-04 20:05:11
【问题描述】:

我对 Python-3 如何以不一致的方式执行列表设置转换感到困惑。当输入列表按降序排序时,它会按升序创建一个集合。当输入列表未排序时,它什么也不做,结果集也未排序。在一种情况下,即使是未排序的列表也会转换为排序集。

# list is unsorted and resulting set is unsorted 
lst1 = [9,100,1]
thisset1 = set(lst1)
print(thisset1)     # 9,100,1

# list is sorted in descending order and 
# resulting set is sorted in ascending order
lst2 = [4,3,2,1]
thisset2 = set(lst2)
print(thisset2)     # 1,2,3,4

# list is sorted in descending order and 
# resulting set is sorted in ascending order
lst4 = [500,400,200]
thisset4 = set(lst4)
print(thisset4)    # 500,400,200

# list is unsorted but resulting set is SORTED in ascending order 
lst3 = [4,1,3,2]
thisset3 = set(lst3)
print(thisset3)

是因为散列吗?

【问题讨论】:

  • 集合不是语义上有序的数据结构,如果你关心它的顺序,那就是使用错误的集合。

标签: python-3.x list set


【解决方案1】:

集合是无序的数据结构。所以顺序是随机的。 让我们举一个你用过的例子。

lst4 = [500,400,200] 
set(lst4)  
{400, 500, 200}

这与你的不同。所以相同输入的顺序可能不同。

【讨论】:

  • 你是对的。当我用 100 次迭代进行测试时,我可以清楚地看到随机性。相同的列表导致不同的集合顺序。谢谢
猜你喜欢
  • 2021-01-08
  • 2023-01-14
  • 1970-01-01
  • 2016-07-05
  • 2018-10-25
  • 2017-04-25
  • 2012-07-13
  • 1970-01-01
  • 2019-04-11
相关资源
最近更新 更多