Python:函数中的返回列表结果问题 [英] Python: Return list result problem in a function

查看:679
本文介绍了Python:函数中的返回列表结果问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用打印功能执行此操作

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'])

我明白了

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')

为什么会这样?

我需要返回函数与打印函数完全一样,我需要在代码上进行更改或重写什么...谢谢...请确实使您的响应尽可能简单,可理解且直截了当.欢呼

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结束函数,而yield创建一个生成器,一次生成一个值:

return ends the function, while yield creates a generator that spits out one value at a time:

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']))

或者,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']))

或仅使用enumerate:

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

在任何情况下,'\n'.join(str(x) for x in iterable)都采用列表形式,然后像print一样将每个项目转换为字符串,然后像多个print语句一样将每个字符串与换行符连接起来.

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.

这篇关于Python:函数中的返回列表结果问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆