繁体   English   中英

从 function 中,如何返回项目位于不同行的列表?

[英]From a function, how do I return a list whose items are on different lines?

看看吃下面的清单

nursery_rhyme = [
'This is the house that Jack built.',
'This is the malt that lay in the house that Jack built.',
'This is the rat that ate the malt that lay in the house that Jack built.',
'This is the cat that killed the rat that ate the malt that lay in the house that Jack built.'
]

下面的 function 应该在指定范围内返回上面列表的行

def recite(start_verse, end_verse):
    lines = []
    start = start_verse
    lines.append(nursery_rhyme[(start-1)])
    while start < end_verse:
        start += 1
        line = nursery_rhyme[start-1]
        lines.append(line)
    return (lines)

正在使用:

print(recite(1,2))

Output:

['This is the house that Jack built.', 'This is the malt that lay in the house that Jack built.']

如何让我的 output 看起来像这样:

[
 'This is the house that Jack built.',
 'This is the malt that lay in the house that Jack built.'
]

你可以试试这样...

def recite(start_verse, end_verse):
  for line in (start_verse-1, end_verse):
    print(nursery_rhyme[line])


recite(1,2)

您可以遍历每个字符串并将其打印出来,而不是一次打印整个列表:

for i in recite(1, 2):
    print(i)

这是一个快速简单的 function 将 output 行,如纸上所示。

下面的 function 使用以下技术:

  • 仅列出对 output 的切片所需的行。
  • print functionsep参数,它告诉print在每个项目之间打印哪个字符,在这种情况下,是一个新行。
  • 'splat' 运算符 ( * ) 扩展(或解包)列表元素,从而使print可以用新行分隔每个元素。

例如:

def recite(lines, start, end):
    print(*lines[start-1:end], sep='\n')

>>> recite(nursery_rhyme, 1, 2)

Output:

This is the house that Jack built.
This is the malt that lay in the house that Jack built.

暂无
暂无

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

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