Вы можете либо собрать все значения и return
их сразу, либо yield
каждое значение одно за другим :
# 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)
Поскольку ваше преобразование отображается непосредственно из одной формы в другую, вы можете выразить обав форме понимания , а также:
all_at_once = [match['champion'] for match in matchList['matches']]
one_after_another = (match['champion'] for match in matchList['matches'])
Хотя оба предоставляют итерируемость, оба не эквивалентны.return
означает, что вы строите весь список заранее, тогда как yield
лениво вычисляет каждое значение.
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)
Когда вы return
список, вы также можете повторно использовать его содержимое,Напротив, когда вы yield
каждое значение, оно исчезает после использования:
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