Python中list和set的區別


轉自http://www.cnblogs.com/soaringEveryday/p/5044007.html

List

字面意思就是一個集合,在Python中List中的元素用中括號[]來表示,可以這樣定義一個List:

L = [12, 'China', 19.998]

可以看到並不要求元素的類型都是一樣的。當然也可以定義一個空的List:

L = []

Python中的List是有序的,所以要訪問List的話顯然要通過序號來訪問,就像是數組的下標一樣,一樣是下標從0開始

>>> print L[0]
12

千萬不要越界,否則會報錯

>>> print L[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

List也可以倒序訪問,通過“倒數第x個”這樣的下標來表示序號,比如-1這個下標就表示倒數第一個元素:

>>> L = [12, 'China', 19.998]
>>> print L[-1]
19.998

-4的話顯然就越界了

>>> print L[-4]

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    print L[-4]
IndexError: list index out of range
>>> 

List通過內置的append()方法來添加到尾部,通過insert()方法添加到指定位置(下標從0開始):

>>> L = [12, 'China', 19.998]
>>> L.append('Jack')
>>> print L
[12, 'China', 19.998, 'Jack']
>>> L.insert(1, 3.14)
>>> print L
[12, 3.14, 'China', 19.998, 'Jack']
>>> 
  注意python中有幾個方法與append類似,但是效果完全不一樣,使用時需根據實際需求選用正確方法
 1.append()  向列表尾部追加一個新元素,列表只占一個索引位,在原有列表上增加
 2.extend() 向列表尾部追加一個列表,將列表中的每個元素都追加進來,在原有列表上增加
      比如 list1=[1, 2, 3]   .list2=[4, 5, 6]
      list1.append(list2) 的結果為[1, 2, 3, [4, 5, 6]]
      list1.extend(list2) 的結果為[1, 2, 3, 4, 5, 6]
 3.+  直接用+號看上去與用extend()一樣的效果,但是實際上是生成了一個新的列表存這兩個列表的和,只能用在兩個列表相加上
 4.+= 效果與extend()一樣,向原列表追加一個新元素,在原有列表上增加

通過pop()刪除最后尾部元素,也可以指定一參數刪除指定位置:

>>> L.pop()
'Jack'
>>> print L
[12, 3.14, 'China', 19.998]
>>> L.pop(0)
12
>>> print L
[3.14, 'China', 19.998]

也可以通過下標進行復制替換

>>> L[1] = 'America'
>>> print L
[3.14, 'America', 19.998]

Set

 set也是一組數,無序,內容又不能重復,通過調用set()方法創建:

>>> s = set(['A', 'B', 'C'])

對於訪問一個set的意義就僅僅在於查看某個元素是否在這個集合里面,注意大小寫敏感:

>>> print 'A' in s
True
>>> print 'D' in s
False

也通過for來遍歷:

s = set([('Adam', 95), ('Lisa', 85), ('Bart', 59)])

for x in s:
    print x[0],':',x[1]

>>>
Lisa : 85
Adam : 95
Bart : 59

通過add和remove來添加、刪除元素(保持不重復),添加元素時,用set的add()方法

>>> s = set([1, 2, 3])
>>> s.add(4)
>>> print s
set([1, 2, 3, 4])

如果添加的元素已經存在於set中,add()不會報錯,但是不會加進去了:

>>> s = set([1, 2, 3])
>>> s.add(3)
>>> print s
set([1, 2, 3])

刪除set中的元素時,用set的remove()方法:

>>> s = set([1, 2, 3, 4])
>>> s.remove(4)
>>> print s
set([1, 2, 3])
如果刪除的元素不存在set中,remove()會報錯:
>>> s = set([1, 2, 3])
>>> s.remove(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 4

所以如果我們要判斷一個元素是否在一些不同的條件內符合,用set是最好的選擇,下面例子:

months = set(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec',])
x1 = 'Feb'
x2 = 'Sun'

if x1 in months:
    print 'x1: ok'
else:
    print 'x1: error'

if x2 in months:
    print 'x2: ok'
else:
    print 'x2: error'

>>>
x1: ok
x2: error

另外,set的計算效率比list高,見http://www.linuxidc.com/Linux/2012-07/66404.htm

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM