def attrgetter(*items):
if any(not isinstance(item, str) for item in items):
raise TypeError('attribute name must be a string')
if len(items) == 1:
attr = items[0]
def g(obj):
return resolve_attr(obj, attr)
else:
def g(obj):
return tuple(resolve_attr(obj, attr) for attr in items)
return g
def resolve_attr(obj, attr):
for name in attr.split("."):
obj = getattr(obj, name)
return obj
operator.itemgetter(*items)
回傳一個使用運算元的 __getitem__()
方法從運算元中獲取 item 的可呼叫物件。如果指定了多個條目,則回傳一個查詢值的 tupple。例如:
在 f = itemgetter(2)
之後,呼叫 f(r)
將回傳 r[2]
。
在 g = itemgetter(2, 5, 3)
之後,呼叫 g(r)
將回傳 (r[2], r[5], r[3])
。
def itemgetter(*items):
if len(items) == 1:
item = items[0]
def g(obj):
return obj[item]
else:
def g(obj):
return tuple(obj[item] for item in items)
return g
傳入的條目可以為運算元的 __getitem__()
所接受的任何型別。dictionary(字典)接受任意可雜湊的值。list、tupple 和字串接受索引或切片:
>>> itemgetter(1)('ABCDEFG')
>>> itemgetter(1, 3, 5)('ABCDEFG')
('B', 'D', 'F')
>>> itemgetter(slice(2, None))('ABCDEFG')
'CDEFG'
>>> soldier = dict(rank='captain', name='dotterbart')
>>> itemgetter('rank')(soldier)
'captain'
使用 itemgetter()
從 tuple 中提取特定欄位的例子:
>>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
>>> getcount = itemgetter(1)
>>> list(map(getcount, inventory))
[3, 2, 5, 1]
>>> sorted(inventory, key=getcount)
[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
operator.methodcaller(name, /, *args, **kwargs)
回傳一個在運算元上呼叫 name method 的可呼叫物件。如果給定額外的引數和/或關鍵字引數,它們也將被傳給該 method。例如:
在 f = methodcaller('name')
之後,呼叫 f(b)
將回傳 b.name()
。
在 f = methodcaller('name', 'foo', bar=1)
之後,呼叫 f(b)
將回傳 b.name('foo', bar=1)
。
def methodcaller(name, /, *args, **kwargs):
def caller(obj):
return getattr(obj, name)(*args, **kwargs)
return caller
原地 (in-place) 運算子
許多運算都有「原地」版本。以下列出的是提供對原地運算子(與一般語法相比)更底層存取的函式,例如 statement x += y
相當於 x = operator.iadd(x, y)
。換一種方式來講就是 z = operator.iadd(x, y)
等價於複合陳述式 z = x; z += y
。
在這些例子中,請注意當呼叫一個原地方法時,運算和賦值是分成兩個步驟來執行的。下面列出的原地函式只執行第一步,即呼叫原地方法,第二步賦值則不加處理。
對於不可變 (immutable) 的目標例如字串、數字和 tupple,更新的值會被計算,但不會被再被賦值給輸入變數:
>>> a = 'hello'
>>> iadd(a, ' world')
'hello world'
'hello'
對於可變 (mutable) 的目標例如 list 和 dictionary,原地方法將執行更新,因此不需要後續賦值操作:
>>> s = ['h', 'e', 'l', 'l', 'o']
>>> iadd(s, [' ', 'w', 'o', 'r', 'l', 'd'])
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
2001-2024, Python Software Foundation.
This page is licensed under the Python Software Foundation License Version 2.
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
See History and License for more information.