python集合,

來源:互聯網
上載者:User

python集合,

1,補充一點列表傳參需要注意的地方:列表傳參,是傳引用

#!/usr/bin/python#coding:utf-8def show( l ):    print '函數裡面'    print id( l )    l[0] = 100a = [ 10, 20, 30 ]print '調用前'print id( a )print '調用後'show( a )print a

執行結果:

ghostwu@ghostwu:~/python/tmp$ !ppython list_arg.py 調用前140000495519000調用後函數裡面140000495519000[100, 20, 30]

2,我們可以在函數裡面對傳遞的列表參數,做一個拷貝,就不會是傳引用了

#!/usr/bin/python#coding:utf-8def show( l ):    b = l[:]    print '函數裡面'    print id( b )    b[0] = 100a = [ 10, 20, 30 ]print '調用前'print id( a )print '調用後'show( a )print a

執行後

ghostwu@ghostwu:~/python/tmp$ python list_arg2.py 調用前140145018864920調用後函數裡面140145018776680[10, 20, 30]

集合:沒有順序的概念,不能進行索引或者切片操作

1、建立集合. set():可變的   不可變的frozenset()

2,集合add與update操作

>>> a = set()>>> type( a )<type 'set'>>>> a.add( 10 )>>> a.add( 20 )>>> aset([10, 20])>>> a.add( 'ghostwu' )>>> aset([10, 20, 'ghostwu'])>>> a.update( 'ghostwu' )>>> aset(['g', 'h', 10, 'o', 's', 20, 't', 'w', 'u', 'ghostwu'])>>> 

update操作,把自身一個個添加到集合

remove操作,刪除一個不存在的元素會報錯

>>> aset(['g', 'h', 10, 'o', 's', 20, 't', 'w', 'u', 'ghostwu'])>>> a.remove( 'ghostwu' )>>> aset(['g', 'h', 10, 'o', 's', 20, 't', 'w', 'u'])>>> a.remove( 20 )>>> aset(['g', 'h', 10, 'o', 's', 't', 'w', 'u'])>>> a.remove( 'ab' )Traceback (most recent call last):  File "<stdin>", line 1, in <module>KeyError: 'ab'>>> 

判斷成員是否存在in, not in

>>> aset(['g', 'h', 10, 'o', 's', 't', 'w', 'u'])>>> 'g' in aTrue>>> 'h' not in a False>>> 10 in aTrue>>> 

集合:交集,並集,差集

交集:

>>> a = set( 'abcd' )>>> b = set( 'bcdef' )>>> a & bset(['c', 'b', 'd'])>>> 

並集:

>>> a | bset(['a', 'c', 'b', 'e', 'd', 'f'])>>> 

差集:

>>> a - bset(['a'])>>> b - aset(['e', 'f'])>>> 

 去重複:

>>> l = [1,2,3]>>> l.append( 1 )>>> l.append( 3 )>>> l[1, 2, 3, 1, 3]>>> a = set( l )>>> aset([1, 2, 3])>>> type( a )<type 'set'>>>> l[1, 2, 3, 1, 3]>>> l = list ( a )>>> l[1, 2, 3]>>> 

frozenset不能進行add,remove操作

>>> s = frozenset( 'abc' )>>> sfrozenset(['a', 'c', 'b'])>>> s.add( 'd' )Traceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'frozenset' object has no attribute 'add'>>> s.remove( 'a' )Traceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'frozenset' object has no attribute 'remove'>>> 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.