python如何输入多个print_如何返回多个值,如python 3中的print?

# initial match list

matchList = {'matches': [{'champion': champ} for champ in (101, 238, 157, None)]}

def all_at_once():

result = []

for match in matchList['matches']:

result.append(match['champion'])

return result

def one_after_another():

for match in matchList['matches']:

yield match['champion']

这两个都提供了一个不可替代的-您可以在

for

循环,传递给

list

或者破坏它们,例如:

for item in one_after_another():

print(item)

print(*all_at_once())

first, second, third, *rest = one_after_another()

print(first, second, third)

由于转换直接从一种形式映射到另一种形式,因此可以在

comprehension form

也:

all_at_once = [match['champion'] for match in matchList['matches']]

one_after_another = (match['champion'] for match in matchList['matches'])

虽然两者都提供了iterables,但两者并不相等。

返回

意味着你预先建立了整个列表,而

产量

懒惰地计算每个值。

def print_all_at_once():

result = []

for i in range(3):

print(i)

result.append(i)

return result

def print_one_after_another():

for i in range(3):

print(i)

yield i

# prints 0, 1, 2, 0, 1, 2

for item in print_all_at_once():

print(item)

# print 0, 0, 1, 1, 2, 2

for item in print_one_after_another():

print(item)

当你

返回

一个列表,你也可以

重新使用

它的内容。相反,当你

产量

每个值在使用后都会消失:

returned = print_all_at_once() # already prints as list is built

print('returned', *returned) # prints all values

print('returned', *returned) # still prints all values

yielded = print_one_after_another() # no print as nothing consumed yet

print('yielded', *yielded) # prints all values and value generation

print('yielded', *yielded) # prints no values

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值