繁体   English   中英

给定一个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.

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