【问题标题】:Function returns only the first element during iteration函数在迭代期间仅返回第一个元素
【发布时间】:2018-05-01 13:09:31
【问题描述】:

这是我目前所拥有的:

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

如何修复它,使其在联系人库中获取多个键和值

【问题讨论】:

  • 欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。
  • 网上有无数的排序教程,还有很多如何重新排列数据集合的例子。参考这些内容后,您究竟在哪里卡住了?
  • 您应该使用 yield 或返回整个列表。
  • return [ (k,)+ v for k, v in contacts ]
  • @COLDSPEED 谢谢我非常感谢您提供的信息和详细分解您所有有效的方法

标签: python function return return-value


【解决方案1】:

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

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 项返回给调用者。一旦函数返回,它不会恢复执行并返回任何您可能期望的更多项目。因此,您只会看到一件商品被退回。

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

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

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

请注意,函数调用周围需要list(...),因为yield 会返回一个生成器,您必须对其进行迭代以获得最终的列表结果。

【讨论】:

  • @COLDSPEED - 两者哪个更好,收益还是回报?我问是因为我最近才开始学习python,还没有看到书中的yield。
  • @O'Neill 我认为返回列表就足够了。但对于大数据,yield 效率更高。
猜你喜欢
  • 1970-01-01
  • 2018-06-20
  • 1970-01-01
  • 2021-01-31
  • 2017-03-29
  • 2022-08-12
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多