python學習記錄-1

來源:互聯網
上載者:User

標籤:

原處修改,快:

 

第一種方式:

>>> a=[1,2,3]

>>> b=a

>>> a.extend([4,5])

>>> a

[1, 2, 3, 4, 5]

>>> b

[1, 2, 3, 4, 5]

第二種方式:

>>> a=[1,2,3]

>>> b=a

>>> a+=[4,5]

>>> a

[1, 2, 3, 4, 5]

>>> b

[1, 2, 3, 4, 5]

 

 

 

合并:

>>> a

[1, 2, 3]

>>> b=a

>>> a=a+[4]

>>> a

[1, 2, 3, 4]

>>> b

[1, 2, 3]

 

 

 

for遍曆字典的兩種方式:

>>> d={‘a‘:1,‘b‘:2,‘c‘:3}

>>> for key in d:

...  print(key,‘=>‘,d[key])

... 

b => 2

a => 1

c => 3

>>> list(d.items())

[(‘b‘, 2), (‘a‘, 1), (‘c‘, 3)]

>>> for (key,value) in d.items():

...  print(key,‘=>‘,value)

... 

b => 2

a => 1

c => 3

 

 

 

for迴圈一般都比while計數器迴圈運行得更快。因為迭代器在python 中是以C語言的速度啟動並執行,而while迴圈版本則是通過python虛擬機器運行python位元組碼的。

 

readlines會一次性講檔案讀入記憶體,不適合大檔案。

 

 

 

列表以及很多其它的內建對象,不是自身的迭代器,因為他們支援多次開啟迭代器。對這樣的對象,我們必須調用iter來啟動迭代:

>>> l=[1,2,3]

>>> iter(l) is l

False

>>> l.__next__()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

AttributeError: ‘list‘ object has no attribute ‘__next__‘

>>> a=iter(l)

>>> a.__next__()

1

>>> next(a)

2

 

 

列表解析的兩種反式:

慢:

>>> L=[1,2,3,4,5]

>>> for i in range(len(L)):

...  L[i]+=10

... 

>>> L

[11, 12, 13, 14, 15]

 

快:

>>> L=[x+10 for x in L]

>>> L

[21, 22, 23, 24, 25]

 

python學習記錄-1

相關文章

聯繫我們

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