函数在迭代过程中仅返回第一个元素 [英] Function returns only the first element during iteration

查看:54
本文介绍了函数在迭代过程中仅返回第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我到目前为止所拥有的:

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')])

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

这是结果

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

推荐答案

这里的问题是返回数据的方式.考虑一个简单的例子:

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')]

正在发生的事情是 return 语句将 first 项返回给调用者.该函数返回后,将不会继续执行,也不会返回您期望的其他任何项目.因此,您只会看到返回的一项.

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.

有两种解决方案.您可以返回 list 中的所有内容,也可以使用 yield 语法.

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

选项1
返回< 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')]


选项2
收益

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')]

请注意,函数调用周围需要 list(...),因为 yield 会导致返回 generator ,您必须进行迭代以获得最终列表结果.

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.

这篇关于函数在迭代过程中仅返回第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆