【问题标题】:How to print the first ten results of the code如何打印代码的前十个结果
【发布时间】:2022-01-16 13:36:16
【问题描述】:

如何只打印程序的前 10 个结果?我尝试创建一个空列表,但无法正确存储结果然后打印它们。

    from nltk.corpus import brown

user_input = input('Input a sequence: ') #ADJ+NOUN+NOUN
User_Input = user_input.split('+')

words = brown.tagged_words(tagset='universal') #to access the POS tags

for i, word in enumerate(words):
    if i+2 < len(words):
        if words[i][1] == User_Input[0] and words[i+1][1] == User_Input[1] and words[i+2][1] == User_Input[2]:
            print(words[i], words[i+1], words[i+2])

【问题讨论】:

  • 欢迎来到 Stackoverflow。请使用可用的格式选项。
  • 请在您的代码周围加上代码引号,将您的问题放在问题正文中并附上一些解释,并提出一个简短的描述性标题,而不是在标题中包含整个正文。

标签: python indexing nltk slice


【解决方案1】:

有很多方法可以做到:

如果包含数据的对象已经支持切片表示法,比如列表,你可以简单地做data[:n],n是你想要的项目数

>>> data=list(range(0,10**6,10))
>>> len(data)
100000
>>> data[:10] 
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
>>> 

在列表的情况下,您会得到一个包含那么多元素的新列表

如果对象不支持切片表示法,或者您不想在列表的情况下在其上使用额外空间,则可以使用 itertools 模块中的 islice

>>> import itertools
>>> for n in itertools.islice(data,10):
        print("item",n)

    
item 0
item 10
item 20
item 30
item 40
item 50
item 60
item 70
item 80
item 90
>>>     

其他选项是在满足条件时中断迭代

>>> for i,n in enumerate(data):
        print("item",n)
        if i>=9:
            break

    
item 0
item 10
item 20
item 30
item 40
item 50
item 60
item 70
item 80
item 90
>>> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-10
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2020-12-28
    相关资源
    最近更新 更多