0

I'm trying to loop through 2 lists and combine the results and write that to a file, however I could find a method to do this yet.

hosts = ['host1', 'host2', 'host3']
ips = ['ip1', 'ip2', 'ip3']
filename = 'devicelist.txt'

with open(filename, 'w') as out_file:
    for i in ips:
        for h in hosts:
            out_file.write(h + ' - ' + i + '\n')

This basically runs through every possible combination, but that's not the result I'm looking for. What I'm looking is like this:

host1 - ip1
host2 - ip2
host3 - ip3
vikdean
  • 23
  • 1
  • 5
  • I read your question again. it seems you are making a list of lists that is usually done with list comprehension see https://stackoverflow.com/questions/21507319/python-list-comprehension-list-of-lists – Abhishek Dujari Mar 29 '18 at 14:04

4 Answers4

1

The problem in this code is that you're first looping over one list, and then over the other. You can easily take care of this by combining both using the zip function. This combines two lists like this:

a = [1,2,3]
b = [4,5,6]
c = zip(a,b)

here

c = [(1, 4), (2, 5), (3, 6)]

Now doing this:

hosts = ['host1', 'host2', 'host3']
ips = ['ip1', 'ip2', 'ip3']

#if the lists don't have the same length, you'll get an incomplete list here!
output = zip(hosts, ips)

Gets you a combined list that you can write to your file using:

with open('devicelist.txt', 'w') as out_file:
    for i in output:
          out_file.write('{} - {} \n'.format(i[0], i[1]))

the '{}'.format(x) outputs a string with x instead of the brackets.

Nathan
  • 3,558
  • 1
  • 18
  • 38
0

You have two lists of same length, So it is just a piece of cake.

You can do it like this,

filename = 'devicelist.txt' 
open(filename, 'w') # Creates File.
hosts = ['host1', 'host2', 'host3']
ips = ['ip1', 'ip2', 'ip3']
with open(filename, 'a') as f:
       for i in range(len(hosts)):
            f.write(hosts[i]+' - '+ips[i])

This should do the Job!

Happy Coding!!

Nikhil.Nixel
  • 555
  • 2
  • 11
  • 25
-1

If the two arrays have the same length you can do:

for i in xrange(length):  # length is any of the arrays length
    out_file.write(hosts[i] + ' - ' + ips[i] + '\n')

this can be simpified to:

newList = [hosts[i] + ' - ' + ips[i] + '\n' for i in xrange(length)]

with open(filename, 'w') as out_file:
    for element in newList:
            out_file.write(element)

check this answer for better methods and more explanation.

-1

Here's a solution:

hosts = ['host1', 'host2', 'host3']
ips = ['ip1', 'ip2', 'ip3']

assert len(hosts) == len(ips) # check that the 2 list are the same lenght

with open('devicelist.txt', 'w') as out_file:
    for i in xrange(len(ips)):
        out_file.write(hosts[i] + ' - ' + ips[i] + '\n')
Nathan
  • 3,558
  • 1
  • 18
  • 38
Yassine Faris
  • 951
  • 6
  • 26