python函数返回列表,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'])

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:

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:

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:

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值