Fallacy11
Fallacy11

Reputation: 610

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.

Upvotes: 0

Views: 447

Answers (2)

Eli Korvigo
Eli Korvigo

Reputation: 10513

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)

P.S.

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. In fact, you don't even use s in your code. You refer to your master lists at each iteration, hence you get them printed entirely every single time.

Upvotes: 0

Stefan van den Akker
Stefan van den Akker

Reputation: 6999

You can use zip:

for ip, vlan, n in zip(networks, vlans, name):
    print ip
    print vlan
    print n

Upvotes: 3

Related Questions