VENTIZ
VENTIZ

Reputation: 5

Displaying the corresponding elements of two lists together

I'm new to Python and I want to match the same index of 2 different arrays and send it to a file but I'm having issues when compiling. This is my idea:

interfaces= ['g0/0','g0/1','g0/2']
nameif = ['inside','outside','dmz']

for i in interfaces:
    for j in nameif:
        if interfaces[i]==nameif[j]:
            g.write ('\ninterface '+ i + j)

I'm expecting to see this in the file:

interface g0/0 inside

interface g0/1 outside

interface g0/2 dmz

But when I run it like that, it says TypeError: list indices must be intergers or slice, not str.

Any idea, how can I achieve this on Python?

Upvotes: 0

Views: 722

Answers (3)

Antimony
Antimony

Reputation: 2240

You don't need to iterate over all indices and then find the matching ones. If you have some index i, you can just access the corresponding item from each list.

for i in range(len(interfaces)):
    g.write ('\ninterface '+ interfaces[i] + nameif[i])

Also, as others have pointed out, you're getting that error because you're trying to use i and j as indices while they are actually elements of the lists that you are iterating over, and hence of string type.

Upvotes: 0

Mike
Mike

Reputation: 794

Your 'i' loop iterates the elements in the 'interfaces' list...and then you try to use those elements as an index, which you cannot do.

What you were probably wanting is a numeric loop, such as:

for i in range(len(interfaces)):

Upvotes: 1

cs95
cs95

Reputation: 402533

There's no way you need two loops for this. Try a zip instead.

for x, y in zip(interfaces, nameif):
    print('interface {} {}'.format(x, y))

interface g0/0 inside
interface g0/1 outside
interface g0/2 dmz

As a tip, you should understand how the for works better. For example,

for x in interfaces:
     print(x)

g0/0
g0/1
g0/2

A for loop iterates over an iterator, not indices. If you want to iterate over both, you can use enumerate:

for i, x in enumerate(interfaces):
     print(i, x)

0 g0/0
1 g0/1
2 g0/2

Upvotes: 1

Related Questions