python學習筆記3

來源:互聯網
上載者:User

標籤:連續   dex   第一個   foo   nts   轉化   產生   ted   lis   

再次重申學習的是某位THU大神,網址貼下

http://nbviewer.jupyter.org/github/lijin-THU/notes-python/tree/master/

只貼了我不太熟悉的 適合有其他程式設計語言基礎的看

Chat 4 list

列表的加法,相當於將兩個列表按順序串連

a = [1, 2, 3]b = [3.2, ‘hello‘]a + bl = [1, 2.0, ‘hello‘]l * 2# 列表與整數相乘,相當於將列表重複相加

我們知道字串是無法直接進行修改的,那麼要修改其中的一個類型怎麼辦呢?

如果轉化list的話,那就簡單許多了

>>> s=‘abcdef‘                  #原字串>>> s1=list(s)                  #將字串轉換為列表>>> s1                         [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘]  #列表的每一個元素為一個字元>>> s1[4]=‘E‘                   #將列表中的第5個字元修改為E>>> s1[5]=‘F‘                   #將列表中的第5個字元修改為E>>> s1[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘E‘, ‘F‘]  >>> s=‘‘.join(s1)               #用空串將列表中的所有字元重新串連為字串>>> s‘abcdEF‘                        #新字串

list當中的整段替換

a = [10, 11, 12, 13, 14]a[1:3] = [1, 2, 3, 4]print a

對於不連續(間隔step不為1)的片段進行修改時,兩者的元素數目必須一致:

否則會報錯

a = [10, 11, 12, 13, 14]a[::2] = [1, 2, 3]a[::2] = []# 上面這一句 右邊為空白,所以無法運行

刪除元素

a = [1002, ‘a‘, ‘b‘, ‘c‘]del a[0]del a[1:]del a[::2]

測試從屬關係

a = [10, 11, 12, 13, 14]print 10 in aprint 10 not in a# 同樣可以用於字串s = ‘hello world‘print ‘he‘ in sprint ‘world‘ not in s

list.count(object) 返回元素的次數

list.index(object) 返回元素第一次

list.append(object) 將元素object添加了列表最後

list.extend(newList) 將newList添加到列表最後,這裡和 list += newList 一樣

l.insert(idx, ob)在索引 idx處插入 ob ,之後的元素依次後移

l.remove(ob)移除元素

l.pop(idx) 將索引處的元素刪除

a = [10, 11, 12, 13, 11]# 在索引 3 插入 ‘a‘a.insert(3, ‘a‘)print a a = [10, 11, 12, 13, 11]# 移除了第一個 11a.remove(11)print aa = [10, 11, 12, 13, 11]a.pop(2)

sorted可以不影響原來的元素

a = [10, 1, 11, 13, 11, 2]b = sorted(a)print aprint b

除了a.reverse()的取反方法,還有如下的方式

a = [1, 2, 3, 4, 5, 6]b = a[::-1]

介紹一個深拷貝和淺拷貝的問題,知道C++應該對這個概念很熟悉

下面這個例子應該非常明顯的

b = [12, 23]a = bb[1] = 99a# 下面這個例子是所謂的深拷貝b = [12, 23]import copya = copy.copy(b)b[1] = 99a# 還有一種deepCopy,是比copy更深的拷貝,對於list內部的list也是深拷貝
Chat 5 tuple and dictionary

與列表相似,元組Tuple也是個有序序列,但是元組是不可變的,用()產生。

t = (10, 11, 12, 13, 14)

一個元素的元組

a = (10,)type(a)# 下面這種寫法其實不是元組a = (10)type(a)

除此之外,還有a.count(obt) a.index(obj)這種和list差不多的功能

下面稍微比較下tuple和list

測試之前我主觀認為tuple的速度是比list快

%timeit可以測試一個時間

%timeit [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]%timeit (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25)
from numpy.random import randvalues = rand(10000,4)lst = [list(row) for row in values]tup = tuple(tuple(row) for row in values)%timeit for row in lst: list(row)%timeit for row in tup: tuple(row)

最後的結論是元組的產生速度會比列錶快很多

下面的時候介紹下dictionary

出於hash的目的,Python中要求這些索引值對的必須是不可變的,而值可以是任意的Python對象。

synonyms = {}synonyms[‘mutable‘] = [‘changeable‘, ‘variable‘, ‘varying‘, ‘fluctuating‘,                       ‘shifting‘, ‘inconsistent‘, ‘unpredictable‘, ‘inconstant‘,                       ‘fickle‘, ‘uneven‘, ‘unstable‘, ‘protean‘]synonyms[‘immutable‘] = [‘fixed‘, ‘set‘, ‘rigid‘, ‘inflexible‘,                          ‘permanent‘, ‘established‘, ‘carved in stone‘]synonyms

dict還可以嵌套dict,如下的例子

# 定義四個字典e1 = {‘mag‘: 0.05, ‘width‘: 20}e2 = {‘mag‘: 0.04, ‘width‘: 25}e3 = {‘mag‘: 0.05, ‘width‘: 80}e4 = {‘mag‘: 0.03, ‘width‘: 30}# 以字典作為值傳入新的字典events = {500: e1, 760: e2, 3001: e3, 4180: e4}events

除了通常的定義方法,還可以通過dict()轉化來產生字典

inventory = dict(    [(‘foozelator‘, 123),     (‘frombicator‘, 18),      (‘spatzleblock‘, 34),      (‘snitzelhogen‘, 23)    ])inventory[‘frombicator‘] += 1# 直接更新每種索引值inventory
person = {}person[‘first‘] = "Jmes"person[‘last‘] = "Maxwell"person[‘born‘] = 1831print personperson_modifications = {‘first‘: ‘James‘, ‘middle‘: ‘Clerk‘}person.update(person_modifications)# 除了正常的person的表示,還可以使用

不知道某種key是否存在?可以嘗試使用

a = {}a["one"] = "this is number 1"a["two"] = "this is number 2"a.get("one")a.get("three", "undefined")# 如果沒有這個key,就輸出undefined

Dictionary可以使用pop刪除元素,這裡和list類似

細心的童鞋應該記得

list的刪除是a.pop(2),刪除第幾個元素

dict的刪除是a.pop("two"), 刪除相應的索引值

a.pop("two", ‘not exist‘)# 如果不存在就輸出not existdel a["one"]# del和pop同樣的功能

d.keys()返回一個由所有鍵組成的列表;

d.values()返回一個由所有值組成的列表;

d.items()返回一個由所有索引值對元組組成的列表;

python學習筆記3

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.