6.00 Introduction to Computer Science and Programming lec5: Objects in Python

來源:互聯網
上載者:User

Lec5 主要介紹了Python中的集合類:數組、列表和詞典。

首先用下面的例子介紹數組:

Test = (1, 2, 3, 4, 5)print Test[0]print Test[1] x = 100 divisors = ()for i in range(1,x):    if x%i == 0:     divisors = divisors+(i,)print divisors 

Python中的數組是immutable的,也就是說是不可改的。這一點和Java、C++都不同,例如在上面的代碼中若執行Test[0] = 0,則Python會報錯。

在上面的代碼中,divisors + (i,)也許有些難懂。在這裡,+是串連符,兩端的運算元都是數組。(i, )是包含一個元素 i 的數組,而(i)並不是一個數組。

繼續用代碼來介紹鏈表:

Techs = ['MIT', 'Cal Tech']Ivys = ['Harward', 'Yale', 'Brown']Univs = []Univs.append(Techs)print 'Univs =', UnivsUnivs.append(Ivys)print 'Univs =', Univsfor e in Univs:    print 'e =', eflat = Techs + Ivysprint 'flat =', flatartSchools = ['RISD', 'Harward']for u2 in artSchools:    if u2 in flat:        flat.remove(u2)print 'flat =', flatflat.sort()print 'flat =', flatflat[1] = 'UMass'print 'flat =', flat

從上面可以看出,List是一個典型的類,有append, remove, sort等方法。而數組則更像Java中的int等primitive類型,只能被操作符操作。

下面通過代碼介紹Dictionary:

EtoF = {'bread': 'du pain', 'wine': 'du vin',\        'eats': 'mange', 'drinks': 'bois',\        'likes': 'aime', 1: 'un',\        '6.00':'6.00'}print EtoFprint EtoF.keys()print EtoF.keysdel EtoF[1]print EtoFD = {1: 'one', 'deux': 'two', 'pi':3.14159}D1 = Dprint D1for k in D1.keys(): print k, '=', D1[k]def translateWord(word, dictionary):    if word in dictionary:        return dictionary[word]    else:        return worddef translate(sentence):    translation = ''    word = ''    for c in sentence:        if c != ' ':            word = word + c        else:            translation = translation + ' '\                          + translateWord(word, EtoF)            word = ''    return translation[1:] + ' ' + translateWord(word, EtoF)print translate('John eats bread')print translate('Steve drinks wine')print translate('John likes 6.00')def keySearch(L, k):    for elem in L:        if elem[0] == k: return elem[1]        return None

Clone方法:

學習過Java的同學應該對這個方法很熟悉,mutable的類需要使用Clone方法才能在記憶體中獲得一個新的對象。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.