Skip to Content
Python 技術手冊 第三版
book

Python 技術手冊 第三版

by lex Martelli, Anna Martelli Ravenscroft, Steve Holden
January 2018
Intermediate to advanced content levelIntermediate to advanced
856 pages
17h 17m
Chinese
GoTop Information, Inc.
Content preview from Python 技術手冊 第三版
84
|
3 章 Python 語言
v2 中迭代
items
keys
values
所回傳的串列不帶有這種限制(在 v3
中,為了同樣的用途,你也能明確地製作出串列,例如
list(D.keys())
)。
直接迭代一個字典
D
v2 中等同於迭代
D.iterkeys()
,而在 v3 中等同於
迭代
D.keys()
v3
dict_...
型別全都是可迭代的(iterable)。
dict_items
dict_keys
也實作了
set
的非變動方法,而且行為很像
frozenset
dict_values
則沒
有,因為跟其他的(還有集合)不同,它可能含有某些重複的項目。
popitem
方法可以用於字典的破壞性迭代(destructive iteration)。
items
popitem
都會以鍵值與值對組(key/value pairs)的形式回傳字典的項目。
popitem
適合用於大型字典的迴圈處理工作,也就是你希望在迴圈跑的過程
中「消耗」字典項目的時候。
D.setdefault(k, x)
回傳的結果與
D.get(k, x)
相同,只不過,如果
k
不是
D
中的鍵值,
setdefault
還會有將
D[k]
繫結到值
x
的副作用。(在現代的
Python 中,
setdefault
已經很少使用,因為涵蓋於後面「defaultdict」中
的型別
collections.defaultdict
能以更優雅且快速的方式提供類似的功能
。)
pop
方法回傳的結果與
get
相同,但如果
k
D
中的鍵值,
pop
還會有移除
D
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

測試驅動開發|使用 Python

測試驅動開發|使用 Python

Harry J.W. Percival
Linux 内核观测技术BPF

Linux 内核观测技术BPF

David Calavera, Lorenzo Fontana

Publisher Resources

ISBN: 9789864766819