1. 程式人生 > >python入門(五):切片列表元祖字典

python入門(五):切片列表元祖字典

chm sin pop hab 包含 out slices 表達 定義

1.切片

針對序列,使用切片可以獲得我們想要的內容

序列:字符串、列表、元祖

特點:可以使用坐標獲取某一個值.坐標是從0開始算

>>> s="0123456789"

>>> print(s[0]) #坐標是從0開始算

0

>>> print(s[9])

9

>>> s=[0,1,2,3,4,5]

>>> print(s[2]) #獲取列表的第三個元素

2

>>> print(s[4]) #獲取列表的第五個元素

4

>>> s=(1,2,3,4,5)

>>> print(s[1]) #獲取元祖的第二個元素

2

>>> print(s[4]) #獲取元祖的第五個元素

5

>>> s

(1, 2, 3, 4, 5)

>>> print(s[-1]) #取最後一個元素

5

>>> print(s[-2]) #取倒數第二個元素

4

>>> list(range(11))

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> s=list(range(11))

>>> s

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> print(s[len(s)//2]) #列表s的長度除以2的商為要取元素的坐標

5

>>> s[5.5]

Traceback (most recent call last): #坐標必須是整數,否則會報錯

File "<stdin>", line 1, in <module>

TypeError: list indices must be integers or slices, not float

類型錯誤:列表索引必須是整數或者片,不能是浮點數

切片:start_pos , end_pos(開區間,不包含), step

>>> a

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> a[1:3:1] #3是開區間,步長是1

[1, 2]

>>> a[0:10:2]

[0, 2, 4, 6, 8]

>>> a[0:10:3]

[0, 3, 6, 9]

>>> a[::5] #如果不寫起始結束,默認從0開始,到最後結束

[0, 5, 10]

>>> a[::] #如果加上步長,全都不寫,模式從0開始,步長是0

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> a[-1:-4] #未寫步長,步長默認為1,-1+1=0,不在-4之內,所

[] #以結果為空

>>> a[-1:-4:-1] #步長為-1,可依次輸出。

[10, 9, 8]

>>> a[::-2] #如果步長為負,輸出結果也為先顯示最後的數據。

[10, 8, 6, 4, 2, 0]

2.列表,可變類型

聲明一個列表:

a=[];

a=[1,1.1,”a”,[1,2],(1,2,3)]

判斷一下列表的類型:isinstance(a,list)

>>> isinstance(a,list)

True

1) 增加

  1. append #在最後的位置加

>>> a=[]

>>> a.append(1)

>>> a

[1]

>>> a.append("a")

>>> a

[1, ‘a‘]

>>> a.append(1+1j)

>>> a

[1, ‘a‘, (1+1j)]

>>> a=[1,2,3]

>>> b=[4,5,6]

>>> a.append(b) #會將列表b變成a的一個元素

>>> a

[1, 2, 3, [4, 5, 6]]

>>> a.extend(b) #extend會將列表b拆開,融合到list a中

>>> a

[1, 2, 3, [4, 5, 6], 4, 5, 6]

2.insert #在指定位置加

>>> a.insert(0,3) #在第0個元素的位置加3

>>> a

[3, 1, ‘a‘, (1+1j)]

>>> a.insert(4,"liuyujing") #在第四個元素的位置加

>>> a

[3, 1, ‘a‘, (1+1j), ‘liuyujing‘]

2) 刪:

  1. del刪除整個列表

>>> del a

>>> a

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name ‘a‘ is not defined #刪除後在調用,提示未定義

2.del刪除指定位置的元素

a=[1, 2, 3]

>>> del a[2] #刪除a中坐標為2的元素

>>> a

[1, 2]

>>> del a[-1] #刪除最後一個元素

>>> a

[1]

>>> a=[1,2,3,4,5]

>>> del a[2:5:2] #刪除指定範圍,且有步長的元素

>>> a

[1, 2, 4]

3.remove指定元素

>>> a=[1,2,3]

>>> a.remove(1) #刪除列表a中的值1

>>> a

[2, 3]

>>> a.remove(4) #a中不存在4,但是要刪除4時,會報錯

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: list.remove(x): x not in list

3) 改 #其實就是指定位置賦值

a=[1, 2, 4]

>>> a[0]=100

>>> a

[100, 2, 4]

>>> a[10]=1 #修改超過範圍的坐標的值,會報錯

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError: list assignment index out of range

>>> [1,2,3]+[4,5,6] #兩個list相加,合並成一個list

[1, 2, 3, 4, 5, 6]

>>> [1,2,3]*3 #相乘,值不變,復制3次

[1, 2, 3, 1, 2, 3, 1, 2, 3]

4) 查

  1. 單個索引查

>>> a[0]

100

  2.切片查

>>> a[:]

[100, 2, 4]

  3.遍歷

>>> for i in a:

... print(i)

...

100

2

4

>>> max([1,2,3]) #查看list中的最大值

3

>>> min([1,2,3]) #查看list中的最小值

1

>>> len([1,2,3]) #查看list的長度

3

>>> max([1,2,3,[4,5,6]]) #list中有子list,無法查看最大值

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: ‘>‘ not supported between instances of ‘list‘ and ‘int‘

5) pop #彈出,且刪掉指定位置的值

a=[100, 2, 4]

>>> a.pop(0) #彈出元素0

100 #元素0為100

>>> a

[2, 4] #已刪除a中的100元素

6) count計數

>>> a=[1,2,1,3,5]

>>> a.count(a) #列表a中a的個數為0

0

>>> a.count(1) #列表a中1的個數為2個

2

>>> a=[1,2,1,3,5,a]

>>> a.count(a)

0

>>> a=[1,2,1,3,5,"a"]

>>> a.count(a)

0

>>> a.count("a")

1

3.元祖

與列表的區別在於元祖不能改,不可變類型

>>> a=()

>>> type(a)

<class ‘tuple‘>

>>> a.append("1") #元祖不支持增

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

AttributeError: ‘tuple‘ object has no attribute ‘append‘

>>> a=1,2 #定義a時,並沒有加(),但實際也是元祖

>>> type(a) #當元素的個數>1時

<class ‘tuple‘>

>>> a=(1) #定義a時,即使有(),但也不是元祖類型

>>> type(a) #當元素的個數=1時

<class ‘int‘>

>>> a=(1,) #如果就想定義一個元素的元祖,需加,

>>> type(a)

<class ‘tuple‘>

>>> a=(0,1,2,3,[4,5,6]) #元祖支持查

>>> a[0] #單個索引查

0

>>> a[0:3] #切片查

(0, 1, 2)

>>> a[3:6]

(3, [4, 5, 6])

>>> a[4]

[4, 5, 6]

>>> a[4][-1] #取出元祖中列表的最後一個元素

6

4.字典,可變類型

>>> d={}

>>> type(d)

<class ‘dict‘>

>>> isinstance(d,dict)

True

1) 增

>>> d[1]="a" #key為1,value為”a”

>>> d

{1: ‘a‘} #key必須為不可變類型

>>> d[[1]]="a" #定義字典時,key被定義了可變類型list會報錯

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: unhashable type: ‘list‘

>>> d[{1:2}]=1 #key必須為不可變類型

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: unhashable type: ‘dict‘

>>> d[(1,2)]=1 #元祖,字符串,數字等均可作為key

>>> d

{(1, 2): 1}

2) 刪

>>> d

{1: 2}

>>> del d[1] #寫明key值,會刪除該key值和value值,字典依然存在

>>> d

{}

>>> d[1]="a"

>>> d

{1: ‘a‘}

>>> del d #刪除字典,且不帶key值,會刪除整個字典

>>> d

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name ‘d‘ is not defined #d未定義

3) 改

>>> d[1]=1

>>> d

{1: 1}

>>> d[1]=2 #當兩個key值相同,但value不同時,會替換舊value

>>> d #所以字典的key會自動替重

{1: 2}

4) 查

>>> d=dict(a=1,b=2,c=3) #快速生成字典的一個表達式

>>> d

{‘a‘: 1, ‘b‘: 2, ‘c‘: 3} #a,b,c均有“”

>>> d=dict("a"=1,"b"=2,"c"=3)

File "<stdin>", line 1

SyntaxError: keyword can‘t be an expression

  1. 遍歷有哪些key值

>>> for i in d: #平常遍歷的方法遍歷字典時,默認遍歷的是key值

... print(i)

...

a

b

c

>>> for i in d.keys(): #d.keys(),遍歷key,註意keys後有()

... print(i)

...

a

b

c

  2.遍歷有哪些values值

>>> for i in d.values():

... print(i)

...

1

2

3

  3.同時遍歷有哪些key值,有哪些value值

>>> for k,v in d.items(): #d,items(),同時遍歷key和value

... print(k,":",v) #items,指的是取一對值

...

a : 1

b : 2

c : 3

>>> list(d.items())

[(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)]

小練習:

  1. 取a=[0,1,2,3,4,5,6,7,8,9,10]中的6,7,8,9這些元素

>>> a[6:9]

[6, 7, 8] #開區間,9不包括,所以錯誤

>>> a[6:10]

[6, 7, 8, 9]

  2.取a=[0,1,2,3,4,5,6,7,8,9,10]中的0,5,10這些元素

>>> a[0:10:5]

[0, 5] #開區間,10不包括,所以錯誤

>>> a[0:11:5]

[0, 5, 10]

  3.取a=[0,1,2,3,4,5,6,7,8,9,10]中,從元素5到元素10步長為3的元素。

>>> a[5:11:3]

[5, 8]

>>> a[5::3]

[5, 8]

  4.取a=[0,1,2,3,4,5,6,7,8,9,10]中,倒取取出10,8,6,4這幾個元素

>>> a[-1:-8:-2]

[10, 8, 6, 4]

  5.s=”gloryroad is good!”,取出road和good中的oo,並拼成字符串

>>> s[5:9]+s[14:16] #切片的使用範圍是字符串,列表,元祖!!

‘roadoo‘

>>> s[5:9]+s[-3:-5:-1] #正數+倒數

‘roadoo‘

  6.s=‘gloryroad is good!‘,倒序輸出gloryroad

>>> s[8::-1] #從前開始數坐標

‘daoryrolg‘

>>> s[-10::-1] #從後開始數坐標

‘daoryrolg‘

  7.求全部元素的和[1,2,1,2,3,3,3,3],提示:遍歷 技術分享圖片
  8.求偶數元素的和[1,2,1,2,3,3,3,3],提示:切片 技術分享圖片 技術分享圖片
  9.統計一下所有數字出現的個數[1,2,1,2,3,3,3,3]
提示:字典 技術分享圖片 技術分享圖片 技術分享圖片

小知識:

  1. 切片倒取必須加步長嗎?

答:是

例如: a=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> a[-4:-1] #這個步長默認為1,可以取出,-4在前,但是是正取!

[7, 8, 9]

  2.切片結束的坐標可超範圍,不會報錯

>>> s=‘gloryroad is good!‘

>>> s[20] #提示超範圍

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError: string index out of range

>>> s[5:20] #切片時,結尾的位置超範圍不會報錯,直至取出最後

‘road is good!‘ #一個元素

  3.切片開始與結束的位置坐標可超範圍,不會報錯

>>> s[20:25] #輸出結果為空,但是未報錯

‘‘

  4.元祖包括了可變類型的時候是可以更改的

>>> a=(1,[1])

>>> a[1].append("a") #這個元祖中的a[1]是列表,便可對a[1]進行更改

>>> a

(1, [1, ‘a‘])

>>> a[1].append(1+1j)

>>> a

(1, [1, ‘a‘, (1+1j)])

可變類型有list和dict等,字符串是不可變的

  5.字符串不可變的原因:只要更改,存儲位置發生變化,實際是兩個不同的字符串。

>>> s="abc"

>>> id(s)

2448316775536 #最初s的id是2448316775536

>>> s=s+"dd"

>>> id(s) #對s進行更改後,id是2448317718064

2448317718064

綜上,字符串不是說進行了更改,而是生成了一個新的字符串。

python入門(五):切片列表元祖字典