简体   繁体   English

从列表中每行打印一个变量

[英]Print single variable per line from list

So I'm pretty new and am still learning but I can't find an answer anywhere..., that being said here is my question: I'm trying to generate output with multiple lists on different line and I want one at a time, I'll post my non-working code, and then a sample of code of one that works with just a single list: 所以我很新,仍然在学习,但我找不到任何答案...,这就是我的问题:我正在尝试生成包含多个位于不同行的列表的输出,我希望一个时间,我将发布无效代码,然后发布仅适用于单个列表的代码示例:

Prints every variable repeatedly on each line the list is called: 在称为列表的每一行上重复打印每个变量:

networks = ["192.168.1.1 255.255.255.0", "192.168.2.1 255.255.255.0", "192.168.3.1 255.255.255.0"]
vlans = ["1001", "1002", "1003"]
name = ["MGMT", "DATA", "VOICE"]

for s in (networks, vlans, name):
    print "vlan %r" % (vlans)
    print "Name %r" % (name)
    print "int vlan %r" % (vlans)
    print " ip add %r" % (networks)

Generates desired output, placing variable sequentially one at a time: 生成所需的输出,一次将变量依次放置一个:

networks = ['192.168.1.1', '192.168.2.1', '192.168.3.1']

for address in networks:
    print "ip add %s" % address
    print "description I can't place multiple variables :'("

Any ideas would be greatly appreciated, ultimately the reason I want to format with list names is the ability to be able to use multiple lists on a single line in this fashion. 任何想法都将不胜感激,最终我想要使用列表名称进行格式化的原因是能够以这种方式在一行上使用多个列表的能力。 Again thank you in advance. 再次感谢您。

Edit: In advance, I understand doing separate for loops for each list, I want this to be done with the order of operations the print statements are made in. 编辑:事先,我知道对每个列表进行单独的for循环,我希望这样做是按照执行打印语句的操作顺序完成的。

You can use zip : 您可以使用zip

for ip, vlan, n in zip(networks, vlans, name):
    print ip
    print vlan
    print n
networks = ["192.168.1.1 255.255.255.0", "192.168.2.1 255.255.255.0", "192.168.3.1 255.255.255.0"]
vlans = ["1001", "1002", "1003"]
names = ["MGMT", "DATA", "VOICE"]

for network, vlan, name in zip(networks, vlans, names):
    print "vlan %r" % (vlan)
    print "Name %r" % (name)
    print "int vlan %r" % (vlan)
    print " ip add %r" % (network)

PS 聚苯乙烯

Regarding your code. 关于您的代码。 for s in (list1, list2...) iterates the tuple of lists, not the the lists themselves, hence s is a list at each iteration. for s in (list1, list2...)会迭代列表的元组,而不是列表本身,因此s是每次迭代时的列表。 In fact, you don't even use s in your code. 事实上,你甚至不使用s在你的代码。 You refer to your master lists at each iteration, hence you get them printed entirely every single time. 您在每次迭代时都参考主列表,因此每次都可以完全打印它们。

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

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