empty_list = []
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
big_birds = ['emu', 'ostrich', 'cassowary']
first_names = ['Graham', 'John', 'Terry', 'Terry', 'Michael']
print(empty_list)
print(weekdays)
print(big_birds)
print(first_names)
[] ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] ['emu', 'ostrich', 'cassowary'] ['Graham', 'John', 'Terry', 'Terry', 'Michael']
可以使用 list() 來作為轉換其他型別至List,或是前面2.3小節提到的字串__split()__函數
print(list('cat'))
a_tuple = ('ready', 'fire', 'aim')
print(list(a_tuple))
birthday = '1/6/1952'
print((birthday.split('/')))
['c', 'a', 't'] ['ready', 'fire', 'aim'] ['1', '6', '1952']
提取內容時跟字串一樣使用[],
index 從0開始,-1為最後一個,
index 數值的範圍請務必在總長度內,不然會出現IndexError。也可以將其修改替換內容。
提取多個以上也如同字串中的用法 __[start : end : step]__,注意這邊只會提取到index為end - 1
XD = ['a', 'b', 'c', 'd']
print(XD[0])
print(XD[1])
print(XD[-1])
print(XD[-2])
XD[0] = 'QQ'
print(XD[0:2])
print(XD[2:-2])
print(XD[::2])
a b d c ['QQ', 'b'] [] ['QQ', 'c']
List裡面可以包含不同類型的物件,當然也包括List
XD = [['a', 'b', 'c'],['d', 'e', 'f'],['g', 'h', 'i']]
print(XD[0])
print(XD[0][1])
['a', 'b', 'c'] b
可以使用List的內建函數append()來向後面添加元素
語法 | 效果 |
---|---|
list.extend()或 += | 合併list |
list.insert() | 在指定位置插入元素,如果位置超過最大長度則放在最後面,故不會飛到很遠去或出錯。 |
del Object | 用來刪除某個位置的元素,剩餘元素會自動往前補填補 |
list.remove() | 用來移除指定元素 |
list.pop() | 為類似剪出的效果,可以將指定位置的元素剪出來,預設index為 -1 |
list.index() | 找查指定元素第一次出現的index |
in Object | 判斷指定元素是否存在 |
list.count() | 計算指定元素出現次數 |
XD = ['a', 'b']
XD2 = ['e', 'f']
print(XD, XD2)
XD.append('QQ~')
print(XD)
XD.extend(XD2)
print(XD)
XD += XD2
print(XD)
XD.append(XD2)
print(XD)
XD.insert(2, 'c')
print(XD)
XD.insert(500, 'ker')
print(XD)
del XD[8]
print(XD)
XD.remove('e')
print(XD)
QQ = XD.pop(3)
print(XD, QQ)
print(XD.index('f'))
print('ker' in XD)
print(XD.count('f'))
['a', 'b'] ['e', 'f'] ['a', 'b', 'QQ~'] ['a', 'b', 'QQ~', 'e', 'f'] ['a', 'b', 'QQ~', 'e', 'f', 'e', 'f'] ['a', 'b', 'QQ~', 'e', 'f', 'e', 'f', ['e', 'f']] ['a', 'b', 'c', 'QQ~', 'e', 'f', 'e', 'f', ['e', 'f']] ['a', 'b', 'c', 'QQ~', 'e', 'f', 'e', 'f', ['e', 'f'], 'ker'] ['a', 'b', 'c', 'QQ~', 'e', 'f', 'e', 'f', 'ker'] ['a', 'b', 'c', 'QQ~', 'f', 'e', 'f', 'ker'] ['a', 'b', 'c', 'f', 'e', 'f', 'ker'] QQ~ 3 True 2
前面2.3節提到的string.join()__,可以用來組裝List成為字串,
書中提到這邊的用法看起來有點彆扭,如果改成__List.join(', ')__會更直覺,
但是當初設計的理念就是join的方法是在字串的型態中,
這樣後面我想要針對List、Tuples或是字串使用字串做組裝,就只要一種方法就好,
不用針對每種型態都去設計一個相同的方法來做使用,如下面範例所示範。
__string.join() 與 __string.split()__兩個為相對應的用法!!!
print(', '.join(['a', 'b', 'c']))
print(', '.join('abc'))
print(', '.join(('a', 'b', 'c')))
print('a, b, c'.split(', '))
a, b, c a, b, c a, b, c ['a', 'b', 'c']
其中的差異在於__sort()__會直接改變輸入的list,__sorted()__則會另外回傳一個排序好的物件,
len()可以獲得list的長度。
L = ['b', 'c', 'a']
L.sort()
print(L)
t = ['b', 'c', 'a']
a = sorted(t)
print(a)
print(len(a))
['a', 'b', 'c'] ['a', 'b', 'c'] 3
使用 '=' 設定變數則會是傳址,等同於前面說的標籤概念,把兩張標籤貼在同一個物件上(number or srting 除外)
這樣當我改變了物件後,則物件上所有的標籤所指到的值都會跟著改變,
若要改成傳值的話可以使用copy() 、 list.list() 與 list[:] 來達到目的
a = [1, 2, 3]
b = a
a[0] = 4
print(a, b)
c = a.copy()
d = list(a)
e = a[:]
a[0] = 'surprises'
print(a, b, c, d, e)
[4, 2, 3] [4, 2, 3] ['surprises', 2, 3] ['surprises', 2, 3] [4, 2, 3] [4, 2, 3] [4, 2, 3]
a = () #空Tuples
b = 'tem', #b:(tem,) 括弧可以省略,但是一個的時候逗號不能省略
c = 'tem1', 'tem2', 'tem3' #('tem1', 'tem2', 'tem3')
d, e, f = c #d:'tem1', e:'tem2', f:'tem3'
print(a)
print(b)
print(c)
print(d, e, f)
() ('tem',) ('tem1', 'tem2', 'tem3') tem1 tem2 tem3
結合以上的用法可以有一個超級方便直覺的用法,任意交換變數間的值。
(在等號右邊的東西會先形成一個Tuples,再分配給前面的變數。)
a = '1'
b = '2'
c = '3'
b, c, a = a, b, c
print(a, b, c)
3 1 2
既然他不能修改等等的那相對於List一定也有其他好處
dic = { 'a':'v','b':'w', } #最後一個逗號可以省略
dic_ = { 'd':'y','c':'x' } #最後一個逗號可以省略
print(dic, dic_)
lol1 = [ ['a', 'b'], ['c', 'd'], ['e', 'f'] ]
lol2 = [ ('a', 'b'), ('c', 'd'), ('e', 'f') ]
lol3 = ( ['a', 'b'], ['c', 'd'], ['e', 'f'] )
print(dict(lol1), dict(lol2), dict(lol3))
tos1 = [ 'ab', 'cd', 'ef' ]
tos2 = ( 'ab', 'cd', 'ef' )
print(dict(tos1), dict(tos2))
print('============分隔線============')
print(dic_['c'])
dic_['c'] = 'z'
print(dic_['c'])
dic.update(dic_)
print(dic)
del dic['d']
print(dic)
print('a' in dic)
print('============分隔線============')
print(dic.keys()) # dict_keys(['a', 'b', 'c'])
print(dic.values()) # ['v', 'w', 'x']
print(list(dic.items())) # [('a', 'v'), ('b', 'w'), ('c', 'x')]
print('============分隔線============')
dic_new = dic
dic_new['a'] = 'n'
print(dic, dic_new)
dic_cp = dic.copy()
dic_cp['a'] = 'm'
print(dic, dic_cp)
dic.clear()
print(dic)
{'a': 'v', 'b': 'w'} {'d': 'y', 'c': 'x'} {'e': 'f', 'a': 'b', 'c': 'd'} {'e': 'f', 'a': 'b', 'c': 'd'} {'e': 'f', 'a': 'b', 'c': 'd'} {'e': 'f', 'a': 'b', 'c': 'd'} {'e': 'f', 'a': 'b', 'c': 'd'} ============分隔線============ x z {'d': 'y', 'a': 'v', 'c': 'z', 'b': 'w'} {'a': 'v', 'c': 'z', 'b': 'w'} True ============分隔線============ dict_keys(['a', 'c', 'b']) dict_values(['v', 'z', 'w']) [('a', 'v'), ('c', 'z'), ('b', 'w')] ============分隔線============ {'a': 'n', 'c': 'z', 'b': 'w'} {'a': 'n', 'c': 'z', 'b': 'w'} {'a': 'n', 'c': 'z', 'b': 'w'} {'a': 'm', 'c': 'z', 'b': 'w'} {}
empty_set = set()
even_numbers = {0, 2, 4, 6, 8}
print(empty_set, even_numbers)
print(set( 'letters' ))
print(set( ['D', 'A', 'P', 'M'] ))
print(set( ('U', 'Echoes', 'Atom') ))
print(set( {'apple': 'red', 'orange': 'orange'} ))
set() {8, 0, 2, 4, 6} {'r', 'e', 'l', 't', 's'} {'D', 'M', 'P', 'A'} {'U', 'Echoes', 'Atom'} {'orange', 'apple'}
dict_of_lists = {'Stooges': ['Moe', 'Curly', 'Larry'],
'Marxes': ['Groucho', 'Chico', 'Harpo'],
'Pythons': ['Chapman', 'Cleese', 'Gilliam', 'Jones', 'Palin']}
print(dict_of_lists)
print(dict_of_lists['Marxes'])
print(dict_of_lists['Marxes'][1])
{'Pythons': ['Chapman', 'Cleese', 'Gilliam', 'Jones', 'Palin'], 'Marxes': ['Groucho', 'Chico', 'Harpo'], 'Stooges': ['Moe', 'Curly', 'Larry']} ['Groucho', 'Chico', 'Harpo'] Chico