简体   繁体   English

Python-遍历嵌套循环

[英]Python - iterating over nested loop

First off i am certain that such a basic thing has been asked before, but i could not find a post about it. 首先,我确定之前已经问过这样一个基本的问题,但是我找不到关于它的文章。

I have this piece of example data: 我有以下示例数据:

'192.168.244.213': ['8', '4', '3', '1', '6', '5', '3', '2', '6', '5'], 
'192.168.244.214': ['6', '8', '7', '6', '5', '4', '2', '7', '5', '5'], 
'192.168.244.215': ['4', '10', '0', '8', '7', '0', '4', '3', '2', '6'], 
'192.168.244.230': ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0']

And i want to print out every line (each line is one dictionary key-value pair) that has a list-value whose list contains any amount of items that is not 0 (in this case, every line except the 4th) 我想打印出具有列表值的每一行(每一行是一个字典键-值对),其列表包含不为0的任何项(在这种情况下,除第四行以外的每一行)

I just cant seem to figure out this seemingly simple thing - what i tried before was those two things: 我似乎无法弄清楚这看似简单的事情-我之前尝试过的是这两件事:

for i in d.keys():
    if "0" not in d[i]:
        print(i, d[i])

This one shows only lists that do not contain 0 AT ALL - so the third line would not be shown, even though it contains non-0 values 此列表仅显示不包含0 AT ALL的列表-即使包含非0值,也不会显示第三行

for i in d.keys():
    for j in d[i]:
        if j is not "0":
            print(i, d[i])

This one DOES show me what i want, but as you can tell, it prints every result way too often - one print for every list value that is not 0. 这确实告诉我我想要什么,但是正如您所知,它以过于频繁的方式打印每个结果-对于每个不为0的列表值打印一次。

Use a dictionary-comprehension: 使用字典理解:

d = {'192.168.244.213': ['8', '4', '3', '1', '6', '5', '3', '2', '6', '5'],
     '192.168.244.214': ['6', '8', '7', '6', '5', '4', '2', '7', '5', '5'],
     '192.168.244.215': ['4', '10', '0', '8', '7', '0', '4', '3', '2', '6'],
     '192.168.244.230': ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0']}

result = {k: v for k, v in d.items() if not all(x == '0' for x in v)}

# {'192.168.244.213': ['8', '4', '3', '1', '6', '5', '3', '2', '6', '5'],
#  '192.168.244.214': ['6', '8', '7', '6', '5', '4', '2', '7', '5', '5'],
#  '192.168.244.215': ['4', '10', '0', '8', '7', '0', '4', '3', '2', '6']}

The above code generates a new dictionary which omits all items where values are all zeros. 上面的代码生成一个新的字典,该字典将忽略所有值为零的所有项目。

Now that you have a dictionary, you can easily do an iteration like so: 现在您有了字典,可以轻松地进行如下迭代:

for k, v in result.items():
    print(k, v)

You can simply iterate over like 您可以像这样简单地进行迭代

def all_zero(arr):
    for i in arr:
        if i != 0:
            return False
    else:
        return True

You can call it on all the lists one by one. 您可以在所有列表上一一调用它。

for i in d.keys():
    all_zero = True
    for j in d[i]:
        if j is not "0":
            all_zero = False
            break
    if not all_zero:
        print(i, d[i])

This may work for almost every language :) 这可能适用于几乎每种语言:)

Your bug is basically just a missing break: 您的错误基本上只是一个缺失的中断:

for i in d.keys():
    for j in d[i]:
        if j != "0":
            print(i, d[i])
            break

However, for conciseness I would recommend you check out the any() function, which does exactly what you want: Return true if any of the elements of the iterable are true (when cast to booleans). 但是,为简洁起见,我建议您检出any()函数,该函数恰好满足您的要求:如果iterable的任何元素为true (当转换为boolean时),则返回true。

Eg: 例如:

for i in d.keys():
    if any(j != "0" for j in d[i]):
        print(i, d[i])

(The j is not "0" generator is only necessary because you have string values. For an int array, any(d[i]) would work.) j is not "0"生成器,仅因为您具有字符串值而才是必需的。对于int数组, any(d[i])可以使用。)

Even more "Pythonic" would be removing the need for a dictionary lookup: 甚至更多的“ Pythonic”将不再需要字典查找:

for i, d_i in d.items():
    if any(j != "0" for j in d_i):
        print(i, d_i)

I like the other answers but I feel like you can get away with something like this as well: 我喜欢其他答案,但我觉得您也可以摆脱类似的情况:

for i in d.keys():
    #If there are as many zeroes as there are elements in the list...
    if d[i].count(0) == len(d[i]):
        #...You might as well skip it :)
        continue
    print(d[i])

Have a look at how I could accomplish this. 看看我怎么能做到这一点。

d = {
    '192.168.244.213': ['8', '4', '3', '1', '6', '5', '3', '2', '6', '5'], 
    '192.168.244.214': ['6', '8', '7', '6', '5', '4', '2', '7', '5', '5'], 
    '192.168.244.215': ['4', '10', '0', '8', '7', '0', '4', '3', '2', '6'], 
    '192.168.244.230': ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
}

for key in d.keys():
    if all( item == '0' for item in d[key]):
        pass
    else:
        print(key, d[key])

You should use all in this case, consider following example: 在这种情况下,应all使用,请考虑以下示例:

digits = ['0', '2', '0', '4', '7', '5', '0', '3', '2', '6']
zeros = ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
print(all([k=='0' for k in digits])) #gives False
print(all([k=='0' for k in zeros])) #gives True

Please remember to deliver [k=='0' for k in ...] to all , as delivering list directly would give True for both digits and zeros , as both contain at least one non-empty str ( str of length 1 or greater). 请记住将[k=='0' for k in ...]传递给all ,因为直接传递列表将对digitszeros给出True ,因为两者都包含至少一个非空str (长度为1str更大)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM