1

Is it possible to search for matches in two lists where a list item contains a matching string, does not equal?

for example:

list_a = [
    'ip prefix-list PL_ABBA seq 5 permit 10.10.10.0/24',
    'ip prefix-list PL_ABBA seq 10 permit 10.20.10.0/24',
    ]

list_b = [
    '10.10.10.0/24',
    '10.20.10.0/24',
    '10.30.10.0/24',
    '10.40.10.0/24',
    ]

10.30.10.0/24 and 10.40.10.0/24 are missing from list_a so I want to return these two as missing?

I could regex out the subnets from list_a to make new_list_a then compare using set? but was wondering if there was an easier method?

Thanks

Chandella07
  • 2,089
  • 14
  • 22
AlexW
  • 2,843
  • 12
  • 74
  • 156

2 Answers2

5

You can use

>>> IPs = {s.rsplit(' ')[-1] for s in list_a}
>>> IPs
>>> {'10.10.10.0/24', '10.20.10.0/24'}
>>> [ip for ip in list_b if ip not in IPs]
>>> ['10.30.10.0/24', '10.40.10.0/24']

IPs is a set (for the O(1) membership test) of the ip addresses, where s.rsplit(' ')[-1] is used to get the IP part of the elements in list_a.

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • @AlexW we only have to iterate once over `list_a` for splitting off the IPs. After that, all `in` checks on `IPs` are O(1). In other words, this code has complexity O(n + m) where n is the length of `list_a` and `m` is the length of `list_b` - thus linear. – timgeb Nov 01 '18 at 17:10
0

Try below example.

result = []

for item in list_b:
    for st in list_a:
        if item in st:
            break
    else:
        result.append(item)
print(result)

Output:

['10.30.10.0/24', '10.40.10.0/24']
Chandella07
  • 2,089
  • 14
  • 22