我需要一个更好的方法来做到这一点。我是编程新手,但我知道这是一种非常低效的方法,我需要一个函数,我只是不知道该怎么做。有什么建议么?我非常感谢任何帮助!
for H in range(0,len(a_list)):
if a_list[H] > list4[0]:
list5 = [number_list[i]]
if function(list1,list5) == list1[1]:
if function(list2,list5)== list2[1]:
if function(list3,list5)== list3[1]:
if function(list4,list5)== list4[1]:
list5.append(input('some input from the user'))
other_function(list5)
if list5[1]== 40:
print ('something something')
break out of EVERY loop
else:
for H in range(0,len(a_list)):
if a_list[H] > list5[0]:
list6 = [number_list[i]]
if function(list1,list6) == list1[1]:
if function(list2,list6)== list2[1]:
if function(list3,list6)== list3[1]:
if function(list4,list6)== list4[1]:
if function(list5,list6)== list5[1]:
list6.append(input('some input from theuser'))
other_function(list6)
if list6[1]== 40:
print ('something something')
break out of EVERY loop
else:
etc. (one extra comparison every time)
最佳答案
使用 all() function测试多个相关条件:
if all(function(lst, list5) == lst[1] for lst in (list1, list2, list3, list4)):
和
if all(function(lst, list6) == lst[1] for lst in (list1, list2, list3, list4, list5)):
和嵌套的if语句一样,all()会短路;一旦任何测试失败,立即返回 False。
此外,直接循环列表,而不是生成一系列索引。如果你正在使用 break,你也不需要使用 else,移除另一层缩进。
您可以通过过滤 a_list 来删除另一个级别:
for H in filter(lambda H: H > list4[0], a_list):
一起,这减少了你的嵌套:
for H in filter(lambda H: H > list4[0], a_list):
list5 = [number_list[i]]
if all(function(lst, list5) == lst[1] for lst in (list1, list2, list3, list4)):
list5.append(input('some input from the user'))
other_function(list5)
if list5[1]== 40:
print ('something something')
break # out of EVERY loop
for J in filter(lambda J: J >list5[0], a_list):
if all(function(lst, list6) == lst[1] for lst in (list1, list2, list3, list4, list5)):
list6.append(input('some input from theuser'))
other_function(list6)
if list6[1]== 40:
print ('something something')
break # out of EVERY loop
# continue here
大概是你的break语句实际使用异常(raise CustomException() and try:, except CustomException: # break out of所有循环都很快),因为常规的break只会停止当前循环。
如果您不断添加更多列表和嵌套,您可能希望使用一个列表来保存所有这些嵌套列表,然后简单地添加到外部列表:
class EndLoops(Exception): pass
stack = [[number_list[0]]]
try:
for i in number_list[1:]:
for H in filter(lambda H: H > stack[-1][0], a_list):
stack.append([i])
if all(function(lst, stack[-1]) == lst[1] for lst in stack[:-1]):
stack[-1].append(input('some input from the user'))
other_function(stack[-1])
if stack[-1][1] == 40:
print ('something something')
raise EndLoops
except EndLoops:
pass # broken out of outer loop
突然间所有的嵌套都消失了;相反,您将嵌套移动到列表的 stack 列表中。
请注意,我不知道您的代码中最外层的循环是什么样的,我只是在黑暗中进行了一次有根据的尝试,但这个想法应该大致正确。
关于Python - 有什么方法可以避免在 for 循环中相互包含多个 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20401260/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代
我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%