【问题标题】:how can i solve this? Python def function [closed]我该如何解决这个问题? Python def 函数
【发布时间】:2019-02-08 20:26:10
【问题描述】:
def LongestWord(sen): 

  # first we remove non alphanumeric characters from the string
  # using the translate function which deletes the specified characters
  sen = sen.translate(None, "~!@#$%^&*()-_+={}[]:;'<>?/,.|`")

  # now we separate the string into a list of words
  arr = sen.split(" ")
  print(arr)
  # the list max function will return the element in arr
  # with the longest length because we specify key=len
  return max(arr, key=len)

**print LongestWord("Argument goes here")**

这条线有什么问题?我怎样才能改变它?我无法理解!这让我真的很不安,因为 Coderbyte.com 上说这是真的而且有效!

【问题讨论】:

  • 您似乎是从函数本身调用函数。正确缩进
  • @shahidammer 不,我认为星号 ** 使它看起来缩进了,但没有它们它会在外部范围内
  • 错误是什么?
  • 您需要 Python 2.7 来运行此代码,而不是 3.x。 translate函数的参数nr发生了变化。
  • 要使其适合 3.x,请查看:stackoverflow.com/questions/23175809/…

标签: python


【解决方案1】:

它工作正常,但不是返回尝试

print max(arr, key=len)

就好像你直接调用函数时不带 print 关键字,它不会显示最大值,或者你可以在单行中同时返回 arr、max 并打印函数输出,所以它看起来像这样:

def LongestWord(sen):
    sen = sen.translate(None, "~!@#$%^&*()-_+={}[]:;'<>?/,.|`")
    arr = sen.split(" ")
    print(arr)
    print max(arr, key=len)


LongestWord("Argument goes here ! @")

注意:它在 Python 2.7 中工作

如果您想使用 Python 3.7 使用以下

to_remove = sen.maketrans("", "", "~!@#$%^&*()-_+={}[]:;'<>?/,.|`")
sen = sen.translate(to_remove)

【讨论】:

  • 它不起作用。错误从代码的第 5 行开始。如果我放括号,它会给我这样的:Traceback(最近一次通话最后一次):文件“/root/.PyCharmCE2018.2/config/scratches/scratch_1.py”,第 8 行,在 LongestWord("Argument goes here !@") 文件 "/root/.PyCharmCE2018.2/config/scratches/scratch_1.py",第 2 行,在 LongestWord 中 sen = sen.translate(None, "~!@#$%^&*()-_ +={}[]:;'?/,.|`") TypeError: translate() 只接受一个参数(给定 2 个)
  • 确保您使用的是 python 2.7 版本,或者您可以像这样使用高于 3.5 的版本 to_remove = sen.maketrans("", "", "~!@#$ %^&*()-_+={}[]:;'?/,.|`") sen = sen.translate(to_remove)
【解决方案2】:

我也不确定你指的是哪条线?也许是最后一行。

如果是这样,您需要在 python 3.x 中为 print 语句加上括号

print(LongestWord("Argument goes here"))

此外,字符串翻译在 python 3 中的工作方式不同

def LongestWord(sen): 

  # first we remove non alphanumeric characters from the string
  # using the translate function which deletes the specified characters
  intab ="~!@#$%^&*()-_+={}[]:;'<>?/,.|`"
  trantab= str.maketrans(dict.fromkeys(intab))

  sen = sen.translate(trantab)

  # now we separate the string into a list of words
  arr = sen.split(" ")
  print(arr)
  # the list max function will return the element in arr

  # with the longest length because we specify key=len
  return max(arr, key=len)

print(LongestWord("Argument. 'Go' @goes here"))

以上在 python 3.6.2 上对我有用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-25
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多