简体   繁体   English

Python:函数中的返回列表结果问题

[英]Python: Return list result problem in a function

If I do this with print function 如果我用打印功能这样做

def numberList(items):
     number = 1
     for item in items:
         print(number, item)
         number = number + 1

numberList(['red', 'orange', 'yellow', 'green'])

I get this 我明白了

1 red
2 orange
3 yellow
4 green

if I then change the print function to return function I get just only this: 如果我然后将打印功能更改为返回功能我只得到这个:

(1, 'red')

why is this so? 为什么会这样?

I need the return function to work exactly like the print function, what do I need to change on the code or rewrite...thanks...Pls do make your response as simple, understandable and straight forward as possible..cheers 我需要返回功能完全像打印功能一样工作,我需要更改代码或重写...感谢...请尽可能简单,易懂和直截了当。

return ends the function, while yield creates a generator that spits out one value at a time: return结束函数,而yield创建一个一次吐出一个值的生成器:

def numberList(items):
     number = 1
     for item in items:
         yield str((number, item))
         number = number + 1

item_lines = '\n'.join(numberList(['red', 'orange', 'yellow', 'green']))

alternatively, return a list: 或者, return一个列表:

def numberList(items):
     indexeditems = []
     number = 1
     for item in items:
         indexeditems.append(str((number, item)))
         number = number + 1
     return indexeditems

item_lines = '\n'.join(numberList(['red', 'orange', 'yellow', 'green']))

or just use enumerate : 或者只使用enumerate

item_lines = '\n'.join(str(x) for x in enumerate(['red', 'orange', 'yellow', 'green'], 1)))

In any case '\\n'.join(str(x) for x in iterable) takes something like a list and turns each item into a string, like print does, and then joins each string together with a newline, like multiple print statements do. 在任何情况下'\\n'.join(str(x) for x in iterable)取类似于列表并将每个项转换为字符串,就像print一样,然后将每个字符串与换行符连接在一起,就像多个print语句一样做。

A return function will return the value the first time it's hit, then the function exits. return函数将在第一次命中时return该值,然后该函数退出。 It will never operate like the print function in your loop. 它永远不会像循环中的print功能一样运行。

Reference doc: http://docs.python.org/reference/simple_stmts.html#grammar-token-return_stmt 参考文档: http//docs.python.org/reference/simple_stmts.html#grammar-token-return_stmt

What are you trying to accomplish? 你想达到什么目的?

You could always return a dict that had the following: 您总是可以return具有以下内容的dict

{'1':'red','2':'orange','3':'yellow','4':'green'}

So that all elements are held in the 1 return value. 这样所有元素都保存在1个返回值中。

The moment the function encounters "return" statement it stops processing further code and exits the function. 当函数遇到“return”语句时,它会停止处理更多代码并退出函数。 That is why it is returning only the first value. 这就是为什么它只返回第一个值。 You can't return more than once from a function. 您不能从函数返回多次。

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

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