Reputation: 687
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
Upvotes: 0
Views: 34
Reputation: 956
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
.
Upvotes: 1
Reputation: 2919
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
Upvotes: 2