python 資料結構

來源:互聯網
上載者:User

標籤: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中被認為是兩個對象。 

  1. class Item(object):  
  2.   
  3.     def __init__(self, foo, bar):  
  4.         self.foo = foo  
  5.         self.bar = bar  
  6.       
  7.     def __repr__(self):  
  8.         return "Item(%s, %s)" % (self.foo, self.bar)  
  9.       
  10. print set([Item(‘1‘, ‘2‘), Item(‘1‘, ‘2‘)])  
  11.   
  12. # 輸出: set([Item(1, 2), Item(1, 2)])  

資料結構中HASH表的設計思路是:

  1. 被插入元素根據hash值決定插入那個桶(通常一個數組)中
  2. 新插入元素根據的equals方法依次比較桶內元素,以確定是否已經存在

在python中如果我們自訂class,則需要添加__hash__和__eq__兩個方法,前者用於決定當前元素在哪個桶,後者決定當前元素是否在桶中已經存在。

修改後的code如下: 

    1. class Item(object):  
    2.     def __init__(self, foo, bar):  
    3.         self.foo = foo  
    4.         self.bar = bar  
    5.       
    6.     def __repr__(self):  
    7.         return "Item(%s, %s)" % (self.foo, self.bar)  
    8.       
    9.     def __eq__(self, other):  
    10.         if isinstance(other, Item):  
    11.             return ((self.foo == other.foo) and (self.bar == other.bar))  
    12.         else:  
    13.             return False  
    14.       
    15.     def __hash__(self):  
    16.         return hash(self.foo + " " + self.bar)  
    17.   
    18. print set([Item(‘1‘, ‘2‘), Item(‘1‘, ‘2‘)])  
    19.   
    20. # 輸出:set([Item(1, 2)])  

python 資料結構

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.