简体   繁体   English

在不使用 *(星号)的情况下解压

[英]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调用并没有推广到具有更多或更少元素的情况:

  • If the input were empty it would fail with TypeError: reduce() of empty sequence with no initial value .如果输入为空,它将失败并TypeError: reduce() of empty sequence with no initial value
  • If it were given a one-item input list it would return a string rather than a boolean True or False .如果给它一个单项输入列表,它将返回一个字符串而不是 boolean TrueFalse
  • If it were given list with 3+ items it would end up comparing strings to booleans and would always result in False .如果给它一个包含 3 个以上项目的列表,它最终会将字符串与布尔值进行比较,并且总是会得到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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM