![](/img/trans.png)
[英]How to write a function that returns matrix with random values from a given range in Python?
[英]Given a Python list, how to write a function that returns a given range of elements?
我有
def findfreq(nltktext, atitem)
fdistscan = FreqDist(nltktext)
distlist = fdistscan.keys()
return distlist[:atitem]
依赖于NLTK软件包中的FreqDist,并且不起作用。 问题似乎是该函数的一部分,其中我尝试使用变量atitem
仅返回列表的前n个项目。 所以我像这样概括这个功能
def giveup(listname, lowerbound, upperbound)
return listname[lowerbound:upperbound]
返回通常的错误
>>> import bookroutines
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "bookroutines.py", line 70
def giveup(listname, lowerbound, upperbound)
^
SyntaxError: invalid syntax
但也希望有一个比Python更流利的同仁的答案。
你需要一个冒号( :
在结束) def
线。
def findfreq(nltktext, atitem):
fdistscan = FreqDist(nltktext)
distlist = fdistscan.keys()
return distlist[:atitem]
Python的函数声明语法为:
def FuncName(Args):
# code
如果将slice
对象传递给operator.itemgetter()
将返回一个对片段进行slice
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.