1

Right now I have a string array and I want to loop through the string array and compare the value at one index with the value at the next index. For example, if I was doing this in Java, the code would be something like this:

string[] some = ["IP", "IP", "ADDRESS", "2342.42.2", "IP", "ASDF"];
for (int i = 0 ; i < some.length() ; i++)
    if (some[i] == "IP" && some[i+1] == "ADDRESS")
        int ipaddress = some[i+2];

I know that Python is a bit different, but basically I am trying to find the first IP ADDRESS. How can I compare the current element and the next one in a loop?

1 Answer 1

1

This is a direct translation of your code. In python enumerate iterates over a list as index,value pairs.

>>> some = ["IP", "IP", "ADDRESS", "2342.42.2", "IP", "ASDF"];
>>> for i,v in enumerate(some):
...     if v=="IP" and some[i+1] == "ADDRESS": 
...         ipaddress = some[i+2]
... 
>>> ipaddress
'2342.42.2'

However you may consider end cases where there is no such stuff. So you may as well so for i,v in enumerate(some[:-2]). This will ensure that you will not get out of the bounds of the list otherwise you will get an IndexError

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah I just figured it out right after I asked the question...silly on my part. I did something like this: for index in range(len(datainarray)): print 'Current string :' , datainarray[index] if datainarray[index] == "IP" and datainarray[index + 1] == "ADDRESS": print "HERES ONE"
Using enumerate is the preferred way in Python
Oh alright. Will look into that and use that instead then!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.