0

I have a function which is aimed to parse a text file, found a regex match (ip + port) and return a list with unique value:

def parser (file):
    ip_list = []
    pattern = re.compile('[0-9]+(?:\.[0-9]+){3}.port.*')
    for i, line in enumerate(open(file)):
        for match in re.finditer(pattern, line):
            ip_list.append(match.group())
    unique_ip = reduce(lambda l, x: l if x in l else l+[x], ip_list,[])
    return [unique_ip]

This works pretty fine, but for some reason I'm unable to iterate on returned list object and get current size. Example, if I print out

print(parser(file))

and I obtain this output:

[['212.162.82.10 port 80', '212.162.81.10 port 8081']]

I get a list size of 1 (despite there's 2 elements):

print(len(parser(file)))
1

I'm not getting where I'm making mistake. thx

2 Answers 2

2

You have an 2 dimensional array with the double brackets [[

Try len(parser(file[0])) instead or update the code by changing return [unique_ip] to return unique_ip

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

Comments

1

If you notice the output has two brackets, which means a list inside of a list. You're iterating the outermost list, which only has one element: the inner list. So the length really is one.

Instead of returning [unique_ip], just do return unique_ip.

Comments

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.