Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

python - Function returns only the first element during iteration

this is what I have so far:

def sort_contacts(sort_contacts):
    contacts = sorted(sort_contacts.items())

    for (k, v) in contacts:
        return list([(k,)+ v])

from test import testEqual

testEqual(sort_contacts({"Summitt, Pat":("1-865-355-4320","pat@greatcoaches.com"),
"Rudolph, Wilma": ("1-410-5313-584", "wilma@olympians.com")}),
[('Rudolph, Wilma', '1-410-5313-584', 'wilma@olympians.com'),
('Summitt, Pat', '1-865-355-4320', 'pat@greatcoaches.com')])
testEqual(sort_contacts({"Dinesen, Isak": ("1-718-939-2548", "isak@storytellers.com")}),
[('Dinesen, Isak', '1-718-939-2548', 'isak@storytellers.com')])

###############

here is the result

Test Failed: expected [('Rudolph, Wilma', '1-410-5313-584','wilma@olympians.com'), ('Summitt, Pat', '1-865-355-4320', 'pat@greatcoaches.com')] but got [('Rudolph, Wilma', '1-410-5313-584', 'wilma@olympians.com')]
    Pass

How can I fix it so that it grabs more than one key and value in the library of contacts

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue here is the way you return your data. Consider a simple example:

In [263]: def foo(data):
     ...:     for k, v in sorted(data.items()):
     ...:         return [(k, ) + v]
     ...:     

In [264]: foo({'a' : ('b', 'c'), 'd' : ('e', 'f')})
Out[264]: [('a', 'b', 'c')]

What's happening is that the return statement returns the first item back to the caller. Once the function returns, it does not resume execution and return any more items as you might expect. Because of this, you only see one item returned.

There are two possibilities as a solution. You could either return everything in a list, or use the yield syntax.

Option 1
return <list>

In [271]: def foo(data):
     ...:     return[(k,) + v for  k, v in sorted(data.items())]
     ...:         

In [272]: foo({'a' : ('b', 'c'), 'd' : ('e', 'f')})
Out[272]: [('a', 'b', 'c'), ('d', 'e', 'f')]

Option 2
yield

In [269]: def foo(data):
     ...:     for k, v in sorted(data.items()):
     ...:         yield (k, ) + v
     ...:     

In [270]: list(foo({'a' : ('b', 'c'), 'd' : ('e', 'f')}))
Out[270]: [('a', 'b', 'c'), ('d', 'e', 'f')]

Note that list(...) is needed around the function call because yield results in a generator being returned, which you must iterate over to get your final list result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...