Python學習筆記(1)---列表和元組

什麼是列表?python

列表是一種數據項構成的有限序列,即按照必定的線性順序,排列而成的數據項的集合。app

列表的介紹ide

1、更新列表函數

1.元素賦值排序

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

>>> a[1]=10 #改變a中第二個值爲10字符串

>>> aget

[1, 10, 4, 5]it

2.增長元素ast

>>> a=[1,10,4,5]

>>> a.append(6) #用法:list.append(obj)

>>> a

[1, 10, 4, 5, 6]

3.刪除元素

>>> a=[1,10,4,5,6]

>>> del a[2] #刪除第三個元素

>>> a

[1, 10, 5, 6]

4.分片賦值

>>> b=list('abc') #list函數將字符串轉化爲列表

>>> b

['a', 'b', 'c']

>>> b[1:1]='d' #使用分片賦值增長元素

>>> b

['a', 'd', 'b', 'c']

>>> b[1:2]='h' #使用分片賦值修改元素

>>> b

['a', 'h', 'b', 'c']

>>> b[2:3]='' #使用分片賦值刪除元素

>>> b

['a', 'h', 'c']

2、列表方法

1.統計元素個數 count

用法:list.count(obj)

>>> a=list('hello,world')

>>> a.count('l')

3

2.在列表末尾追加另外一個序列 extend

用法:list.extend(seq)

>>> a=['hello']

>>> b=['world']

>>> a.extend(b)

>>> a

['hello', 'world']

注:可用分片賦值實現同等效果>>> a[len(a):]=b

與鏈接符號 +的區別

>>> a=['hello']

>>> b=['world']

>>> a+b

['hello', 'world']

>>> a #extend已將a的值改變

['hello']

3.查找第一個匹配的元素index

用法:list.index(obj)

>>> a=['hello', 'world']

>>> a.index('hello')

0

4.插入 insert

用法 list.insert(index,obj)

>>> a=['hello', 'world']

>>> a.insert(0,'goodmoring') #插在0的位置上

>>> a

['goodmoring', 'hello', 'world']

5.移除元素 pop (注:惟一一個技能修改元素又能返 回元素值的方法)

用法:list.pop(obj=list[-1])

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

>>> x.pop() #不加參數,刪除最後一個值,並返回元素值

3

>>> print(x)

[1, 2]

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

>>> y.pop(1) #添加參數1,刪除編號爲1的元素值

2

>>> print(y)

[1, 3]

6.移除列表中第一個匹配項 remove

用法:list.remove(obj)

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

>>> x.remove(2)

>>> print(x)

[1, 3, 2] #只刪除第一個匹配值2

7.反向列表中的元素 reverse

用法:list.reverse()

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

>>> x.reverse()

>>> print(x)

[3, 2, 1] #順序取反

8.排序 sort

用法:list.sort(func) func爲可選參數

>>> x=[4,7,2,5]

>>> y=x[:] #此處與y=x的區別:y=x指向的是同一個列表,若不分片賦予,則x一樣被排序

>>> y.sort()

>>> print(y)

[2, 4, 5, 7]

>>> print(x)

[4, 7, 2, 5]

一樣的操做的方法可以使用sorted

用法:sorted(list)

>>> x=[4,7,2,5]

>>> y=sorted(x)

>>> print(x)

[4, 7, 2, 5]

>>> print(y)

[2, 4, 5, 7]

sort可選參數有兩個,即key和reverse

>>> field=['study','python','is','happy']

>>> field.sort(key=len) #按照長度進行排序

>>> field

['is', 'study', 'happy', 'python']

>>> field.sort(key=len,reverse=True) #按照長度進行反向排序

>>> field

['python', 'study', 'happy', 'is']

9.清空列表 clear

用法:list.clear

>>> field

['python', 'study', 'happy', 'is']

>>> field.clear()

>>> field

[]

10.複製列表 copy ,相似於a[:]

用法:list.copy

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

>>> y=x.copy()

>>> y

[1, 2, 3]

3、元組

元組與列表相似,可是元組的元素不能修改

1.建立元組:用逗號分隔一些值,則自動建立元組

>>> 1,2,3

(1, 2, 3)

>>> 1,

(1,) #逗號很重要,沒有逗號是建立不了元組的

>>> 1

1

使用tuple函數建立元組

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

>>> tuple(x) #能夠將列表改爲元組

(1, 2, 3)

2.元組基本操做

(1)訪問元組

>>> x=(1,2,3,4)

>>> x[1]

2

>>> x[2:]

(3, 4)

(2)鏈接組合元組

>>> x=(1,2,3,4)

>>> y=(5,6)

>>> x+y

(1, 2, 3, 4, 5, 6)

(3)刪除元組

>>> y=(5,6)

>>> del y

>>> y #此時元組已不存在

Traceback (most recent call last):

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

NameError: name 'y' is not defined

相關文章
相關標籤/搜索