標籤:lse 符號 sel 切片 重複 set集合 定義 item 決定
一.Python 集合set()添加刪除、交集、並集、集合操作詳解
在Python set是基礎資料型別 (Elementary Data Type)的一種集合類型,它有可變集合(set())和不可變集合(frozenset)兩種。建立集合set、集合set添加、集合刪除、交集、並集、差集的操作都是非常實用的方法。
1.python set類是在python的sets模組中,大家現在使用的python2.7.x中,不需要匯入sets模組可以直接建立集合。
>>>set(‘boy‘)
set([‘y‘, ‘b‘, ‘o‘])
set()的值不能重複
2.集合添加、刪除
python 集合的添加有兩種常用方法,分別是add和update。
集合add方法:是把要傳入的元素做為一個整個添加到集合中,例如:
>>> a = set(‘boy‘)
>>> a.add(‘python‘)
>>> a
set([‘y‘, ‘python‘, ‘b‘, ‘o‘])
3.集合update方法:是把要傳入的元素拆分,做為個體傳入到集合中,例如:
>>> a = set(‘boy‘)
>>> a.update(‘python‘)
>>> a
set([‘b‘, ‘h‘, ‘o‘, ‘n‘, ‘p‘, ‘t‘, ‘y‘])
4.集合刪除操作方法:remove
set([‘y‘, ‘python‘, ‘b‘, ‘o‘])
>>> a.remove(‘python‘)
>>> a
set([‘y‘, ‘b‘, ‘o‘])
5.python set() 集合操作符號、數學符號
集合的交集、合集(並集)、差集,瞭解python集合set與列表list的這些非常好用的功能前,要先瞭解一些集合操作符號
可變集合python set是www.iplaypy.com玩蛇網python學習交流平台,初期python學習中比較能接觸到的。像列表、字典、字串這類可迭代的對像都可以做為集合的參數。set集合是無序的,不能通過索引和切片來做一些操作。
python中set集合如何決定是否重複?
看下面代碼,兩個值相同的Item對象,添加到set中被認為是兩個對象。
- class Item(object):
-
- def __init__(self, foo, bar):
- self.foo = foo
- self.bar = bar
-
- def __repr__(self):
- return "Item(%s, %s)" % (self.foo, self.bar)
-
- print set([Item(‘1‘, ‘2‘), Item(‘1‘, ‘2‘)])
-
- # 輸出: set([Item(1, 2), Item(1, 2)])
資料結構中HASH表的設計思路是:
- 被插入元素根據hash值決定插入那個桶(通常一個數組)中
- 新插入元素根據的equals方法依次比較桶內元素,以確定是否已經存在
在python中如果我們自訂class,則需要添加__hash__和__eq__兩個方法,前者用於決定當前元素在哪個桶,後者決定當前元素是否在桶中已經存在。
修改後的code如下:
- class Item(object):
- def __init__(self, foo, bar):
- self.foo = foo
- self.bar = bar
-
- def __repr__(self):
- return "Item(%s, %s)" % (self.foo, self.bar)
-
- def __eq__(self, other):
- if isinstance(other, Item):
- return ((self.foo == other.foo) and (self.bar == other.bar))
- else:
- return False
-
- def __hash__(self):
- return hash(self.foo + " " + self.bar)
-
- print set([Item(‘1‘, ‘2‘), Item(‘1‘, ‘2‘)])
-
- # 輸出:set([Item(1, 2)])
python 資料結構