[英]Unpack without using * (asterisk)
If I want to keep things functional, and do not want to use *
in the middle, then what is the equivalent substitute function?如果我想保持功能,并且不想在中间使用
*
,那么等效的替代品 function 是什么? for example,例如,
import operator as op
print(op.eq(*map(str.upper, ['a', 'A'])))
how do I avoid using *
here?我如何避免在这里使用
*
?
I created a function, like,我创建了一个 function,比如,
def unpack(args):
return *args
but it gives syntax error, print(*args)
works but return
fails但它给出了语法错误,
print(*args)
有效但return
失败
functools.reduce
can be used to apply a function of two arguments to an iterable cumulatively, which would work for your example case functools.reduce
可用于将两个 arguments 中的一个 function 累积应用于可迭代对象,这适用于您的示例案例
import operator as op
from functools import reduce
print(reduce(op.eq, map(str.upper, ['a', 'A'])))
You could use reduce
to check if all of the mapped elements are equal to each other.您可以使用
reduce
来检查所有映射元素是否彼此相等。
from functools import reduce
print(reduce(op.eq, map(str.upper, ['a', 'A'])))
This isn't really a sensible thing to do, though.不过,这并不是一件明智的事情。 I say this because the
reduce
call above doesn't generalize to cases with more or fewer elements:我这样说是因为上面的
reduce
调用并没有推广到具有更多或更少元素的情况:
TypeError: reduce() of empty sequence with no initial value
.TypeError: reduce() of empty sequence with no initial value
。True
or False
.True
或False
。False
.False
。 If your plan is to call op.eq
with exactly two operands, no more and no less, then unpacking with *
is appropriate.如果您的计划是使用恰好两个操作数调用
op.eq
,不多也不少,那么使用*
解包是合适的。 Even in a functional context.即使在功能上下文中。
One way to achieve this is by creating a function named apply
.实现此目的的一种方法是创建一个名为
apply
的 function。
def apply(func, args):
return func(*args)
apply(op.eq, map(str.upper, ['a', 'A']))
You can solve this with reduce
if there is some safe value you know will not occur.如果有一些您知道不会出现的安全值,您可以使用
reduce
来解决这个问题。 For example, if you know None
will not be in your list, you can do例如,如果您知道
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.