为什么list(set(a+b))返回有序列表?它总是返回一个有序的列表吗?

2024-04-16 21:43:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个整数列表。我将列表中的元素组合起来,创建一个没有重复的新列表。我想把新名单整理一下。但当我尝试使用set组合时,它会返回一个有序列表。我想知道为什么它会返回一个有序的列表?这总是真的吗?你知道吗

我尝试了不同的list值,它返回了有序的list

a = [1,1,2,3,5,8,13,14,15,16]
b = [1,1,2,3,4,5,6,7,8,9,10,11,12]
c = list(set(a+b))
print(c)

结果是:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

Tags: 元素列表整数整理listprintset名单
2条回答

Python中的集合不按顺序排列:

Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

(source)

以下是示例:

a = list(reversed([1,1,2,3,5,4498576,8,13,14,15,16]))
b = [1,345,132,36465,7,8,9,10,11,12]
c = list(set(a+b))
print(c)

印刷品:

[1, 2, 3, 132, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 4498576, 36465, 345]

如果要对列表进行排序,应手动执行:

c.sort()
print(c)

[1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 132, 345, 36465, 4498576]

因为集合是无序的,所以在将集合强制转换为list之后得到的列表不可能是有序的。你知道吗

从文档:https://docs.python.org/3/tutorial/datastructures.html#sets

A set is an unordered collection with no duplicate elements.

下面是一个非常简单的例子,其中order失败

a = [1,5]
b = [1,10,20]
c = list(set(a+b))
print(c)
#[1, 10, 20, 5]

要对组合列表排序,只需使用sorted

In [2]: a = [1,5]                                                                                                                             

In [3]: b = [1,10,20]                                                                                                                         

In [5]: c = list(set(a+b))                                                                                                                    

In [6]: sorted(c)                                                                                                                             
Out[6]: [1, 5, 10, 20]

相关问题 更多 >