Python筆記:string,tuple,list,dictionary的區別(之二,高階用法與型別轉換)

lyckatil發表於2018-05-17

上一篇《Python筆記:string,tuple,list,dictionary的區別(之一,基本用法與區別)》講述了這四種型別的基本用法與區別,本篇講述的是高階用法與型別轉換。關於list的更多的高階用法在下一篇筆記中有詳細演示。《List的高階用法 (aliasing, mutability, cloning詳解)》

tuple的用法

平時寫程式碼tuple用的不多。具體的用法在MIT的python課程裡提到過兩種。

  1. 定義函式的返回值時,用tuple可以返回多個值。但是我發現list也有這個功能,可能tuple的不可修改性更適合完成這個場景。
#used to return more than one value from a function
def quotient_and_remainder(x, y):
    q = x // y
    r = x % y
    return(q, r)
result = quotient_and_remainder(4,5)
print(result)
(0, 4)

2.互換賦值(swap),python的這種操作可以減少一個臨時變數的使用。這種用法同樣可以用在list型別上。

x_tuple = ('a',1)
y_tuple = ('b',2)
(x_tuple, y_tuple)  = (y_tuple, x_tuple)
print(x_tuple)
print(y_tuple)
('b', 2)
('a', 1)

list 的用法

list作為一種常見object,有很多的method可以用。

x_list = ['Peggy','Susie','Daniel']
y_list = ['Pedro','Rebecca']
print(x_list)
print(y_list)
['Peggy', 'Susie', 'Daniel']
['Pedro', 'Rebecca']
Expression Result
x_list.append(‘George’) x_list = [‘Peggy’, ‘Susie’, ‘Daniel’, ‘George’]
x_list.pop() x_list = [‘Peggy’, ‘Susie’, ‘Daniel’]
x_list.extend(y_list) x_list = [‘Peggy’, ‘Susie’, ‘Daniel’, ‘Pedro’, ‘Rebecca’]
x_list.remove(‘Daniel’) x_list = [‘Peggy’, ‘Susie’, ‘Pedro’, ‘Rebecca’]
del(x_list[1]) x_list = [‘Peggy’, ‘Pedro’, ‘Rebecca’]
x_list.append('George')
print(x_list)
x_list.pop()
print(x_list)
x_list.extend(y_list)
print(x_list)
x_list.remove('Daniel')
print(x_list)
del(x_list[1])
print(x_list)
['Peggy', 'Susie', 'Daniel', 'George']
['Peggy', 'Susie', 'Daniel']
['Peggy', 'Susie', 'Daniel', 'Pedro', 'Rebecca']
['Peggy', 'Susie', 'Pedro', 'Rebecca']
['Peggy', 'Pedro', 'Rebecca']
  1. append(),無論輸入是element還是list,都會當成element。
  2. '+'的作用類似於extend,輸入都是list,然後把裡面的element新增到list裡面。

string 和list 之間的轉換,split(),join() 用於文字分析

  1. string可以使用split()函式,將其中每一個單詞分離成單獨元素,結果是list型別。
text_string = 'Who knows what will happen in the future?'
text_string.split()[-1]
'future?'
text_list = text_string.split()
text_list
['Who', 'knows', 'what', 'will', 'happen', 'in', 'the', 'future?']
  1. list可以使用join()函式,將很多個字串用指定的符號連結起來,返回字串型別
text_string_rejoin = ' '.join(text_list)
text_string_rejoin
'Who knows what will happen in the future?'

生成dictionary的方法

  1. 通過字串生成字典,在文字處理中常見。
data = 'the quick brown fox jumps over a lazy dog.'
chars = list(set(data))
data_size, vocab_size = len(data), len(chars)
print('There are %d total characters and %d unique characters in your data.' % (data_size, vocab_size))
There are 42 total characters and 28 unique characters in your data.
char_to_ix = { ch:i for i,ch in enumerate(sorted(chars)) }
ix_to_char = { i:ch for i,ch in enumerate(sorted(chars)) }
print(ix_to_char)
print(char_to_ix)
{0: ' ', 1: '.', 2: 'a', 3: 'b', 4: 'c', 5: 'd', 6: 'e', 7: 'f', 8: 'g', 9: 'h', 10: 'i', 11: 'j', 12: 'k', 13: 'l', 14: 'm', 15: 'n', 16: 'o', 17: 'p', 18: 'q', 19: 'r', 20: 's', 21: 't', 22: 'u', 23: 'v', 24: 'w', 25: 'x', 26: 'y', 27: 'z'}
{' ': 0, '.': 1, 'a': 2, 'b': 3, 'c': 4, 'd': 5, 'e': 6, 'f': 7, 'g': 8, 'h': 9, 'i': 10, 'j': 11, 'k': 12, 'l': 13, 'm': 14, 'n': 15, 'o': 16, 'p': 17, 'q': 18, 'r': 19, 's': 20, 't': 21, 'u': 22, 'v': 23, 'w': 24, 'x': 25, 'y': 26, 'z': 27}
  1. 通過兩個同樣長度的list來生成字典
names = ["Peggy", "Susie", "Daniel"]
animals = ["pig", "sheep", "dog"]

最直接的想法是分別對names,和animals做遍歷賦值

names_animals = {}
for i in range(len(names)):
    names_animals[names[i]] = animals[i]
print(names_animals)
{'Peggy': 'pig', 'Susie': 'sheep', 'Daniel': 'dog'}

另一種方法,是呼叫zip函式將兩個list合併,再做for迴圈。這種方法更像python的風格。

names_animals = {}
names_animals_zipped = zip(names, animals)
names_animals = { name:animal for name,animal in names_animals_zipped }
print(names_animals)
{'Peggy': 'pig', 'Susie': 'sheep', 'Daniel': 'dog'}

###參考連結

  1. Python - Lists https://www.tutorialspoint.com/python/python_lists.htm

相關文章