如何在python中只进行一次嵌套for循环打印

时间:2015-07-30 00:34:45

标签: json python-3.x dictionary pretty-print

我试图让我的for循环打印请求只有一次,但它似乎做了两次。我该如何防止这种情况?

import json

list_1 = ['name1','name2',]
list_2 = ['1.1.1.1','2.2.2.2',]

username = 'john'
password = 'test_password'

for x in list_1:
    for y in list_2:
        x = {'device_type': 'juniper', 'ip': y, 'username': username, 'password': password, 'port': 9822,'verbose': False,}
        print (json.dumps(x, indent=1))

期望的结果

        {
 "device_type": "juniper",
 "ip": "1.1.1.1",
 "password": "test_password",
 "port": 9822,
 "verbose": false,
 "username": "john"
}
{
 "device_type": "juniper",
 "ip": "2.2.2.2",
 "password": "test_password",
 "port": 9822,
 "verbose": false,
 "username": "john"
}

2 个答案:

答案 0 :(得分:0)

那是因为内循环发生了两次。

你有2个JSON对象,它们都有不同的"ip"键,我会将它们推送到循环中的数组,然后在循环完成后打印我想要的元素,这样你就可以有更多的控制权如果你需要它,你也可以参考它。

此外,您在这里使用了两个不同上下文中的变量x,第二个x应该被命名为其他内容。

答案 1 :(得分:0)

这给了我想要的东西

import json
import itertools

list_1 = ['name1','name2',]
list_2 = ['1.1.1.1','2.2.2.2',]

username = 'john'
password = 'test_password'

for x, y  in zip(list_1,list_2):
    x = {'device_type': 'juniper', 'ip': y, 'username': username, 'password': password, 'port': 9822,'verbose': False,}
    print (json.dumps(x, indent=1))
相关问题