首頁  >  文章  >  後端開發  >  python中list函數和se函數t的區別

python中list函數和se函數t的區別

尚
原創
2019-06-29 14:09:143468瀏覽

python中list函數和se函數t的區別

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

L = [12, 'China', 19.998]

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

>>> print L[0]
12

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

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

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']
>>>

2、 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 sset([1, 2, 3])

如果刪除的元素不存在set中,remove()會報錯:

>>> s = set([1, 2, 3])
>>> s.remove(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>K
eyError: 4

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

months = set([&#39;Jan&#39;,&#39;Feb&#39;,&#39;Mar&#39;,&#39;Apr&#39;,&#39;May&#39;,&#39;Jun&#39;,&#39;Jul&#39;,&#39;Aug&#39;,&#39;Sep&#39;,&#39;Oct&#39;,&#39;Nov&#39;,&#39;Dec&#39;,])
x1 = &#39;Feb&#39;
x2 = &#39;Sun&#39;
if x1 in months:
    print &#39;x1: ok&#39;
else:
    print &#39;x1: error&#39;
if x2 in months:
    print &#39;x2: ok&#39;
else:
    print &#39;x2: error&#39;
>>>
x1: ok
x2: error

更多Python相關技術文章,請訪問Python教學欄位進行學習!

以上是python中list函數和se函數t的區別的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:python如何計時下一篇:python如何計時