[英]Unpack multiple dictionaries as functional arguments without repeating double asterisk
[英]Unpack without using * (asterisk)
如果我想保持功能,並且不想在中間使用*
,那么等效的替代品 function 是什么? 例如,
import operator as op
print(op.eq(*map(str.upper, ['a', 'A'])))
我如何避免在這里使用*
?
我創建了一個 function,比如,
def unpack(args):
return *args
但它給出了語法錯誤, print(*args)
有效但return
失敗
functools.reduce
可用於將兩個 arguments 中的一個 function 累積應用於可迭代對象,這適用於您的示例案例
import operator as op
from functools import reduce
print(reduce(op.eq, map(str.upper, ['a', 'A'])))
您可以使用reduce
來檢查所有映射元素是否彼此相等。
from functools import reduce
print(reduce(op.eq, map(str.upper, ['a', 'A'])))
不過,這並不是一件明智的事情。 我這樣說是因為上面的reduce
調用並沒有推廣到具有更多或更少元素的情況:
TypeError: reduce() of empty sequence with no initial value
。True
或False
。False
。 如果您的計划是使用恰好兩個操作數調用op.eq
,不多也不少,那么使用*
解包是合適的。 即使在功能上下文中。
實現此目的的一種方法是創建一個名為apply
的 function。
def apply(func, args):
return func(*args)
apply(op.eq, map(str.upper, ['a', 'A']))
如果有一些您知道不會出現的安全值,您可以使用reduce
來解決這個問題。 例如,如果您知道None
不會出現在您的列表中,您可以這樣做
import functools
mylist = list(map(str.upper, ['a', 'A']))
result = functools.reduce(lambda x, y: x if x == y else None, mylist)
print('all equal' if result != None else 'some differ')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.