Python學習筆記4 進階特性_20170618

來源:互聯網
上載者:User

標籤:exce   print   迴圈   int   ict   iterator   enum   catch   bre   

# 切片(擷取list / tuple / 字串 中指定的元素)

l = list(range(10))l[0:3]l[:3] # 0可以省略l[:] # 全部l[3:] # 最後的可以省略l[-2:-1] # 負數下標,見python筆記2中介紹l[-10:] # 取最後10個數l[::2] # 所有數,每個兩個取出

 

# 迭代

  • 通過 for ... in ...
  • 可迭代對象:list、tuple、字串已經在pythonb筆記2中提到了。
  • 判斷是否可迭代
from collections import Iterableisinstance(‘abc‘, Iterable)
  • 將 list 轉化成可以使用下標操作
for i, value in enumerate([‘A‘,‘B‘,‘C‘]) :    print(i, value)
  • 同時引用兩個變數
for x,y in [(1,2), (3,4)] :    print(x, y)

 

# 列表產生式(一句話產生需要的 list)

  • range
list(range(2,10))
  • 通用方法
[x*x for x in range(1,10)][x*x for x in range(1,10) if x%2 == 0][m+n for m in ‘ABCD‘ for n in ‘12345‘]
  • dict 情況
d = {‘x‘:‘A‘, ‘y‘:‘B‘}>>>[k+‘=‘+c for k,v in d.items()][‘x=A‘, ‘y=B‘]

 

# 產生器(得到的是“函數”規則,而非結果)

  • 列表生產式相關(將中括弧改成小括弧)
g = (x*x for x in range(10))>>>next(g) # 獲得產生器的結果
  • 函數相關(在需要停的位置添加yield,比如改 print 為 yield)
# 函數def dplist(l) :     for sub in l :        print(sub)    return ‘done‘# 產生器def dplist(l) :     for sub in l :        yield(sub)    return ‘done‘

  添加了 yield 的地方更像是一個函數的運行斷點,每次運行都是承接上次的運行結果。不會迴圈,到末了就會報終止錯誤,該錯誤可以catch

  • 捕獲錯誤
>>>def dplist() :     for sub in range(10) :        yield(sub)    return ‘done‘>>>g = dplist()
>>>while True: try: x=next(g) print(‘g = ‘, x) except StopIteration as e: print(‘Genearator return vaue : ‘, e.value) break

 

# 迭代器

可以用於for迴圈的:list、tuple、dict、set、str、產生器(generator)等

  • 以上可以直接作用於 for 的,稱為“可迭代對象”(Iterable)

  判斷方法

from collections import Iterable>>>isinstance([], Iterable)
  • “迭代器對象”(Iterator)
from collections import Iterator>>>isinstance([], Iterator)

產生器才是“迭代對象”,可以使用next

list、tuple、dict、set、str、產生器(generator)是“可迭代”對象,不能使用next

  • Iterable轉化為Iterator,使用 iter()
isinstance(iter([]), Iterator)
  • 迭代器什麼用:

  迭代器因為是一種規則,所以理論上可以表示所有的整數。但是諸如 list 就不可以。

 

Python學習筆記4 進階特性_20170618

聯繫我們

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