且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python中的集合和列表有什么区别?

更新时间:2023-11-06 15:01:04

有很大的不同.

  1. 集不能包含重复项
  2. 集合是无序的
  3. 为了在集合中查找元素,使用了哈希查找(这就是为什么集合无序的原因).这使得__contains__(in运算符)的集合比列表更有效.
  4. 集合只能包含可哈希项(请参阅#3).如果尝试:set(([1],[2])),您将得到一个TypeError.
  1. Sets can't contain duplicates
  2. Sets are unordered
  3. In order to find an element in a set, a hash lookup is used (which is why sets are unordered). This makes __contains__ (in operator) a lot more efficient for sets than lists.
  4. Sets can only contain hashable items (see #3). If you try: set(([1],[2])) you'll get a TypeError.

在实际应用中,列表很容易排序和排序,而当您不想重复且不关心顺序时,可以很好地使用集合.

In practical applications, lists are very nice to sort and have order while sets are nice to use when you don't want duplicates and don't care about order.

还请注意,如果您不关心订单等,可以使用

new_set = myset.intersection(mylist)

以获得setlist之间的交集.

to get the intersection between a set and a list.