Python基礎:1.數據類型(列表)

提示:python版本爲2.7,windows系統python

1.列表(List)shell

  List,是一個有序的集合,能夠添加、刪除其中的元素。windows

1 >>> colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple']
2 >>> colors
3 ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple']

  colors就被成爲List,而 【'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple'】則被稱爲元素。app

1 >>> type(colors)
2 <type 'list'>

  用len()方法能夠獲取到colors的長度spa

1 >>> len(colors)
2 7

  獲取元素,則用索引0,1,2,3,4....不能超過colors的長度。從0開始,最後則是len(colors) - 1。code

1 >>> colors[0]
2 'red'
3 >>> colors[1]
4 'orange'
5 >>> colors[5]
6 'indigo'
7 >>> colors[6]
8 'purple'

  超出長度則會報錯。blog

1 >>> colors[7]
2 
3 Traceback (most recent call last):
4   File "<pyshell#10>", line 1, in <module>
5     colors[7]
6 IndexError: list index out of range

 當索引爲負數時,則從後往前取,-1開始到-len(colors)索引

1 >>> colors[-1]
2 'purple'
3 >>> colors[-7]
4 'red'
1 >>> colors[-8]
2 
3 Traceback (most recent call last):
4   File "<pyshell#13>", line 1, in <module>
5     colors[-8]
6 IndexError: list index out of range

 取索引爲2與-2開始的全部unicode

1 >>> colors[2:]
2 ['yellow', 'green', 'blue', 'indigo', 'purple']
3 >>> colors[-2:]
4 ['indigo', 'purple']

 取從索引爲3的數據到第5個,第一個索引爲0開始,第二個索引爲1開始的。it

1 >>> colors[3:5]
2 ['green', 'blue']

 添加元素,在末尾

1 >>> colors.append('pink')
2 >>> colors
3 ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple', 'pink']

 指定位置添加元素

1 >>> colors.insert(1, 'white')
2 >>> colors
3 ['red', 'white', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple', 'pink']

 刪除元素,在末尾

1 >>> colors.pop()
2 'pink'
3 >>> colors
4 ['red', 'white', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple']

 刪除指定元素,則爲pop(索引)

1 >>> colors.pop(1)
2 'white'
3 >>> colors
4 ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple']

 修改元素,直接賦值修改

1 >>> colors[0] = 'white'
2 >>> colors
3 ['white', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple']

 一個List中的類型不必定都是相同的,也能夠有數字,列表等在裏面

1 >>> colors.append(['red', 'black'])
2 >>> colors
3 ['white', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple', ['red', 'black']]
4 >>> type(colors[7])
5 <type 'list'>
6 >>> colors[7][0]
7 'red'
8 >>> colors[7][1]
9 'black'

 pop是刪除元素並返回這個元素,若是不須要返回還能夠用del

1 >>> del colors[0]
2 >>> colors
3 ['orange', 'yellow', 'green', 'blue', 'indigo', 'purple', ['red', 'black']]

 List的操做符

1 >>> # 加號
2 >>> colors + ['white']
3 ['orange', 'yellow', 'green', 'blue', 'indigo', 'purple', ['red', 'black'], 'white']
1 >>> # *號
2 >>> colors * 2
3 ['orange', 'yellow', 'green', 'blue', 'indigo', 'purple', ['red', 'black'], 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple', ['red', 'black']]
1 >>> # in
2 >>> 'orange' in colors
3 True
4 >>> 'red' in colors
5 False

提示:中文輸出的是unicode,元素則是中文

1 >>> money = ['人民幣', '美圓']
2 >>> money
3 ['\xc8\xcb\xc3\xf1\xb1\xd2', '\xc3\xc0\xd4\xaa']
1 >>> print money[0]
2 人民幣
3 >>> print money[1]
4 美圓
相關文章
相關標籤/搜索