繁体   English   中英

如何将其写入 Python 3 中的 function 中?

[英]How do I write this into a function in Python 3?

我将如何将其写入给出相同 output 的 function 中?

from nltk.book import text2

sorted([word.lower() for word in text2 if len(word)>4 and len(word)<12])

我不确定我理解你是否正确。

from nltk.book import text2

def my_func():
    return sorted([word.lower() for word in text2 if len(word)>4 and len(word)<12])

my_func()

函数使用特殊关键字def定义,后跟函数名和括号中的参数。 function 的主体必须缩进。 Output 通常使用return -keyword 传递。 对于这行特定的代码,您可以将其包装为:

from nltk.book import text2

def funcName():
   return sorted([word.lower() for word in text2 if len(word)>4 and len(word)<12])

其中 funcName 可以用任何其他词替换,最好是更准确地描述 function 所做的事情。

要使用 function,您需要添加一行funcName() 然后将执行function,执行后程序返回到调用funcName的行,并用function的返回值替换它。

您可以在文档中找到有关函数的更多信息。

欢迎来到StackOverflow ,不幸的是,为您编写代码不是我们的工作,而是帮助您了解您在哪里遇到了一些错误。

您要做的是学习如何将字符串lowercase 、编写条件(如length > 4 && < 12 )以及对 arrays sort

这些是 python 的一些基本且易于学习的功能,查找这些文档可以为您提供答案。 一旦您编写了自己的 python 代码,我们可以更好地帮助您获得解决方案并指出任何缺陷。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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