问题
I'm trying to unpack some list which I've yielded within get_item()
function. I know I can get desired result If I used return
instead of yield
.
I've tried:
def get_item():
yield ["k","y","t"]
if __name__ == '__main__':
for item in get_item():
print(item)
Output I'm getting:
['k', 'y', 't']
Output I wanna get:
k
y
t
What possible change should I bring about to get the desired result keeping yield
as it is?
回答1:
As of Python 3.3, you can use yield from
:
def get_item():
yield from ["k","y","t"]
if __name__ == '__main__':
for item in get_item():
print(item)
Output:
k
y
t
yield from is a new trick introduced in Python 3.3, a short part of it:
For simple iterators, yield from iterable is essentially just a shortened form of for item in iterable: yield item:
(emphasis mine)
回答2:
Desired result you can get with *
operator:
def get_item():
yield ["k","y","t"]
if __name__ == '__main__':
print('\n'.join(*get_item()))
Prints:
k
y
t
回答3:
Try Below:
def get_item():
for _ in ["k","y","t"]:
yield _
if __name__ == '__main__':
for item in get_item():
print(item)
来源:https://stackoverflow.com/questions/56985094/trouble-unpacking-list-in-a-customized-way