【问题标题】:Using map with additional parameters - python使用带有附加参数的地图 - python
【发布时间】:2014-10-03 06:34:59
【问题描述】:

我有一个测量文本长度的功能:

def length(text, option='char'):
  if option == 'char':
    return len(text) - text.count(' ')
  elif option == 'token':
    return text.count(' ') + 1

我可以得到字符文本长度:

texts = ['this is good', 'foo bar sentence', 'hello world']
text_lens = map(length, texts)
print text_lens

但是当我使用map时,如何在函数中指定第二个参数呢?

以下代码:

texts = ['this is good', 'foo bar sentence', 'hello world']
text_lens = map(length(option='token'), texts)
print text_lens

给出这个错误:

TypeError: length() takes at least 1 argument (1 given)

【问题讨论】:

    标签: python list python-2.7 map typeerror


    【解决方案1】:

    在大多数情况下,列表理解/生成器比map 更可取。它提供了地图的所有功能以及一些附加功能。

    text_lens = [length(item, option="token") for item in texts]
    

    【讨论】:

      【解决方案2】:

      或者,您可以使用lambda

      text_lens = map(lambda x: length(x, 'token'), texts)
      
      text_lens = map(lambda x: length(x, option='token'), texts)
      

      【讨论】:

      • 我喜欢lambda,但我的合作者不喜欢,叹息...现在只能使用functools.partial...
      • @alvas,没问题。顺便说一句,有时你不能使用functools.partial。例如,如果length 函数没有关键字参数:def length(text, option):,则不能将partial 用于option
      • @falsetru:如果option 没有默认值,您仍然可以将option='token' 指定为部分。当您尝试指定中间位置参数或某些用 C 编写的函数具有的仅位置参数时,就会出现问题。
      【解决方案3】:

      使用functools.partial:

      text_lens = map(functools.partial(length, option='token'), texts)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-27
        • 2023-03-09
        • 2018-05-24
        相关资源
        最近更新 更多