python 循环嵌套 continue_Python:如何继续嵌套for循环?(Python: How to continue a nested for loop? [duplicate])...

Python:如何继续嵌套for循环?(Python: How to continue a nested for loop? [duplicate])

我正在尝试循环一个具有未知数量的嵌套层的字典。

我想编写一个循环遍历每一层的函数,直到最后。

我相信这里需要一个递归函数,但我想知道如何做到这一点。

这是代码逻辑:

for levelone in file:

for leveltwo in levelone:

for levelthree in leveltwo:

for levelfour in levelthree:

....

你们有什么感想?

I'm trying loop through a dict which has an unknown number of nested layers.

I want to write a function which loops through each layer until the very end.

I believe a recursive function is required here but I would like some advice on how to do it.

here's the code logic:

for levelone in file:

for leveltwo in levelone:

for levelthree in leveltwo:

for levelfour in levelthree:

....

What do you guys think?

原文:https://stackoverflow.com/questions/21094368

2020-01-02 21:01

满意答案

要递归地执行此操作,您需要测试每个值以查看它是否也是一个dict,这在python中有点难看,可能效率不高。 如果是,则再次调用该函数并将该返回与我们到目前为止的结果相结合。 如果它不是一个字典,那么你就在底层,可以随心所欲地做任何事情。

def recurseDict(nested_dict):

output = []

for key, value in nested_dict.iteritems():

if isinstance(value,dict):

output = output + recurseDict(value)

else:

# Do whatever you want here, I'll just add the values to a list

output.append(nested_dict[key])

return output

样本输入和输出:

In [28]: a = {'blue': 4, 'green': {'yellow': {'black': 16}}, 'red': 3}

In [29]: recurseDict(a)

Out[29]: [4, 16, 3]

To do this recursively you need to test each value to see if it's also a dict, which is a bit ugly in python and probably not very efficient. If it is, you call the function again on it and combine that return with what we have so far. If it's not a dict, you're at the bottom layer and can do whatever you'd like with the value.

def recurseDict(nested_dict):

output = []

for key, value in nested_dict.iteritems():

if isinstance(value,dict):

output = output + recurseDict(value)

else:

# Do whatever you want here, I'll just add the values to a list

output.append(nested_dict[key])

return output

Sample input and output:

In [28]: a = {'blue': 4, 'green': {'yellow': {'black': 16}}, 'red': 3}

In [29]: recurseDict(a)

Out[29]: [4, 16, 3]

2014-01-13

相关问答

可能不是你所希望的,但是通常你会在将find设置为True之后break for word1 in buf1:

find = False

for word2 in buf2:

...

if res == res1:

print "BINGO " + word1 + ":" + word2

find = True

break #

for y in range(years):

y += 1

for m in range(month):

rain = float(input('How many inch of rainfall have fallen: '))

total_rain += rain

print("In the year", y,"There will be:", total_rain," inches of rain")

#reset variab...

更新:这个问题是我关于这个问题的文章的灵感。 谢谢你的伟大的问题! “继续”和“休息”只不过是“goto”的愉快语法。 显然,他们给他们可爱的名字,限制他们的使用到特定的控制结构,他们不再画“所有gotos都是坏的所有的时间”人群的愤怒。 如果你想做的是一个继续到外部的,你可以简单地在外部循环的顶部定义一个标签,然后“goto”那个标签。 如果你觉得这样做并不妨碍代码的可理解性,那么这可能是最方便的解决方案。 不过,我会以此为机会考虑您的控制流程是否会从一些重构中受益。 每当我在嵌套循环中有条件的...

players[players_id]['gyms_visited']返回一个列表,因此gym == players[players_id]['gyms_visited']总是评估为False 。 您应该检查使用的会员资格: if gym in players[players_id]['gyms_visited']:

...

players[players_id]['gyms_visited'] returns a list so gym == players[players_id]['...

将内部循环分解为函数可以提高可读性,具体取决于变量如何纠结。 function processRow($reader) {

$row = @{}

for ($i = 0; $i -lt $reader.FieldCount; $i++)

{

if(-not something...) { return $null }

# process row

}

$row

}

while ($reader.Read()) {

$r...

一个简单的解决方法是测试临时布尔值(found_),如下所示: import csv

# Create Dictionary structure of csv file 2

with open("dict.csv", "rb") as fp:

dic_file = csv.reader(fp,)

dict1 = {}

for d in dic_file:

dict1[d[1]] = d[0]

print dict1

found_ = None #not n...

首先,了解在while循环中的break语句之后不能执行任何行。 因此,多次休息和继续将无法工作。 你需要重构你的代码。 就个人而言,我会建议执行try except语句,或者将一些代码放入函数中,这样当您想停止循环并将变量作为指示函数被调用的外部循环的指示时,您可以return 。 另一种选择可以不使用中断,而是继续,使用while循环检查的变量或变量集来决定是否应该继续。 因此,在你的if和exitfirstloop = True ,你可以设置exitfirstloop = True等,并在w...

在阅读了这个问题的评论( 被其作者删除 )并进行了一些研究之后,我发现还有continue参数就像break一样。 我们可以像这样continue添加数字: while($something) {

foreach($array as $value) {

if($ok) {

continue 2;

// continue the while loop

}

foreach($value as $val) {

if(...

要递归地执行此操作,您需要测试每个值以查看它是否也是一个dict,这在python中有点难看,可能效率不高。 如果是,则再次调用该函数并将该返回与我们到目前为止的结果相结合。 如果它不是一个字典,那么你就在底层,可以随心所欲地做任何事情。 def recurseDict(nested_dict):

output = []

for key, value in nested_dict.iteritems():

if isinstance(value,dict):

...

像这样的东西: shape = input("Please enter your choice of shape? ")

nthTime = ["second","third","fourth","fifth","sixth"]

undesired_shapes = ["octagon","heptagon","hexagon"]

indx = 0

while shape.lower() not in undesired_shapes:

print("Please selec...

相关文章

Here are something that need to take care of when y

...

abs(x) 说明:abs(x)返回x的绝对值,如果参数是复数,则返回复数的模; 参数x:整

...

pychseg - A Python Chinese Segment Project - Google

...

Python 字符串操作,字符串序列用于表示和存储文本,python中字符串是不可变的,一旦声明,不能

...

Python 编程语言具有很高的灵活性,它支持多种编程方法,包括过程化的、面向对象的和函数式的。但最重

...

python2和python3的区别,1.性能 Py3.0运行 pystone benchmark的速

...

pro-du-cer n. 1. Someone from a game publisher who

...

Data Week: Becoming a data scientist Data Pointed,

...

python里的字典就像java里的HashMap,以键值对的方式存在并操作,其特点如下:通过键来存取

...

python的官网:http://www.python.org/ 有两个版本,就像struts1和st

...

最新问答

如果启用了复制处理程序,请确保将其置于其中一个安全角色之后。 我见过人们做的另一件事是在不同的端口上运行admin。 最好在需要auth的页面上使用SSL,这样你就不会发送明确的密码,因此管理和复制将发生在8443上,而常规查询将在8080上发生。 如果您要签署自己的证书,请查看此有用的SO页面: 如何在特定连接上使用不同的证书? I didn't know that /admin was the context for SOLR admin because /admin does not re

第一:在您的样本中,您有: 但是你在询问 //td[@class=‘CarMiniProfile-TableHeader’] (注意TableHeader中的大写'T')。 xpath区分大小写。 第二:通过查询// td [@ class ='CarMiniProfile-TableHeader'] / td,你暗示你在外部td中有一个'td'元素,而它们是兄弟姐妹。 有很多方法可以在这里获得制作和模型

这是你的答案: http://jsfiddle.net/gPsdk/40/ .preloader-container { position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; background: #FFFFFF; z-index: 5; opacity: 1; -webkit-transition: all 500ms ease-out;

问题是,在启用Outlook库引用的情况下, olMailItem是一个保留常量,我认为当您将Dim olMailItem as Outlook.MailItem ,这不是问题,但是尝试设置变量会导致问题。 以下是完整的解释: 您已将olMailItem声明为对象变量。 在赋值语句的右侧,在将其值设置为对象的实例之前,您将引用此Object 。 这基本上是一个递归错误,因为你有对象试图自己分配自己。 还有另一个潜在的错误,如果之前已经分配了olMailItem ,这个语句会引发另一个错误(可能是

我建议使用wireshark http://www.wireshark.org/通过记录(“捕获”)设备可以看到的网络流量副本来“监听”网络上发生的对话。 当您开始捕获时,数据量似乎过大,但如果您能够发现任何看起来像您的SOAP消息的片段(应该很容易发现),那么您可以通过右键单击并选择来快速过滤到该对话'关注TCP Stream'。 然后,您可以在弹出窗口中查看您编写的SOAP服务与Silverlight客户端之间的整个对话。 如果一切正常,请关闭弹出窗口。 作为一个额外的好处,wireshar

Android默认情况下不提供TextView的合理结果。 您可以使用以下库并实现适当的aligntment。 https://github.com/navabi/JustifiedTextView Android Does not provide Justified aligntment of TextView By default. You can use following library and achieve proper aligntment. https://github.com/

你的代码适合我: class apples { public static void main(String args[]) { System.out.println("Hello World!"); } } 我将它下载到c:\ temp \ apples.java。 以下是我编译和运行的方式: C:\temp>javac -cp . apples.java C:\temp>dir apples Volume in drive C is HP_PAV

12个十六进制数字(带前导0x)表示48位。 那是256 TB的虚拟地址空间。 在AMD64上阅读wiki(我假设你在上面,对吗?)架构http://en.wikipedia.org/wiki/X86-64 12 hex digits (with leading 0x) mean 48 bits. That is 256 TB of virtual address space. Read wiki on AMD64 (I assume that you are on it, right?) ar

这将取决于你想要的。 对象有两种属性:类属性和实例属性。 类属性 类属性对于类的每个实例都是相同的对象。 class MyClass: class_attribute = [] 这里已经为类定义了MyClass.class_attribute ,您可以使用它。 如果您创建MyClass实例,则每个实例都可以访问相同的class_attribute 。 实例属性 instance属性仅在创建实例时可用,并且对于类的每个实例都是唯一的。 您只能在实例上使用它们。 在方法__init__中定

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值