草庐IT

python - super 简单的嵌套 Pythonic for-in 循环无法正常运行......与输入有关

coder 2023-11-03 原文

我有一段不工作的简单代码,我无法开始弄清楚原因。

代码如下:

def myFunction(otherDictionary, mongoDbCollection):

    for p in otherDictionary:

        print('hi')

        for d in mongoDbCollection:

            print('hello')

显然,最终目标不是打印一堆 hi's 和 hello's,而是在循环机制似乎无法正常运行时纯粹出于调试目的而这样做。

当我沮丧地调用这个函数时,打印了一个 hi,然后是所有的 hello,然后是其余的 his。或者像这样:

hi
hello
hello
hello
hello
hi
hi
hi
hi

而不是:

hi
hello
hello
hello
hello
hi
hello
hello
hello
hello

等等......

它肯定与函数的输入有关,因为当我将 otherDictionary 和 mongoDbCollection 分别更改为 [1,2,3,4,5] 以调试此问题时,它按预期打印了 hi's 和 hello's。

输入中可能有什么会导致此类问题?

mongoDbCollection = 来 self 的 mongo 数据库的集合

otherDictionary 只是一个简单的字典,其中包含关键字和每个关键字的相应计数,如下所示:

{ 'randomKey': 10, 'otherRandomKey': 3, 'evenMoreRandomKey': 14 }

key 中的奇怪字符/符号会导致这样的错误吗?

我完全被难住了!代码太简单了,无法正常工作...

最佳答案

我不使用 mongoDB,所以我在这里可能完全偏离了基础但是:

有没有可能 mongoDbCollection 是一个生成器?生成器只能迭代一次。当您第二次尝试对其进行迭代时,它将无法进行并且基本上是一个空的可迭代对象。

这会导致类似于您在问题中显示的行为:初始 "hi" 将被打印一次, mongoDbCollection 将通过打印 进行迭代"hello" x 次,然后 "hi" 将在第一个 for 循环的剩余部分打印。

它看起来像这样:

hi
hello
hello
hello
# "hello" however many times are in mongoDbCollection ...
hi
hi
hi
# "hi" however many times are in otherDictionary ...

要修复它,您必须创建一个可以无限次迭代的对象(例如,列表或字典,任何与 mongoDbCollection 最匹配的对象)。

def myFunction(otherDictionary, mongoDbCollection):
    collection = list(mongoDbCollection) # or use dict or some other iterable object
    for p in otherDictionary:
        print('hi')
        for d in collection:
            print('hello')

关于python - super 简单的嵌套 Pythonic for-in 循环无法正常运行......与输入有关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45645415/

有关python - super 简单的嵌套 Pythonic for-in 循环无法正常运行......与输入有关的更多相关文章

  1. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  3. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  4. ruby - 树顶语法无限循环 - 2

    我脑子里浮现出一些关于一种新编程语言的想法,所以我想我会尝试实现它。一位friend建议我尝试使用Treetop(Rubygem)来创建一个解析器。Treetop的文档很少,我以前从未做过这种事情。我的解析器表现得好像有一个无限循环,但没有堆栈跟踪;事实证明很难追踪到。有人可以指出入门级解析/AST指南的方向吗?我真的需要一些列出规则、常见用法等的东西来使用像Treetop这样的工具。我的语法分析器在GitHub上,以防有人希望帮助我改进它。class{initialize=lambda(name){receiver.name=name}greet=lambda{IO.puts("He

  5. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  6. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  7. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

  8. ruby-on-rails - Rails 3 I18 : translation missing: da. datetime.distance_in_words.about_x_hours - 2

    我看到这个错误:translationmissing:da.datetime.distance_in_words.about_x_hours我的语言环境文件:http://pastie.org/2944890我的看法:我已将其添加到我的application.rb中:config.i18n.load_path+=Dir[Rails.root.join('my','locales','*.{rb,yml}').to_s]config.i18n.default_locale=:da如果我删除I18配置,帮助程序会处理英语。更新:我在config/enviorments/devolpment

  9. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  10. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

随机推荐