方法1:使用list.index
:
def match(strs, actual):
seen = {}
act = actual.split('/')
for x in strs.split('/'):
if x in seen:
#if the item was already seen, so start search
#after the previous matched index
ind = act.index(x, seen[x]+1)
yield ind
seen[x] = ind
else:
ind = act.index(x)
yield ind
seen[x] = ind
...
>>> p1 = '/foo/baz/myfile.txt'
>>> p2 = '/bar/foo/myfile.txt'
>>> actual = '/foo/bar/baz/myfile.txt'
>>> list(match(p1, actual)) #ordered list, so matched
[0, 1, 3, 4]
>>> list(match(p2, actual)) #unordered list, not matched
[0, 2, 1, 4]
>>> p1 = '/foo/bar/bar/myfile.txt'
>>> p2 = '/bar/bar/baz/myfile.txt'
>>> actual = '/foo/bar/baz/bar/myfile.txt'
>>> list(match(p1, actual)) #ordered list, so matched
[0, 1, 2, 4, 5]
>>> list(match(p2, actual)) #unordered list, not matched
[0, 2, 4, 3, 5]
方法2:使用defaultdict
and deque
:
from collections import defaultdict, deque
def match(strs, actual):
indexes_act = defaultdict(deque)
for i, k in enumerate(actual.split('/')):
indexes_act[k].append(i)
prev = float('-inf')
for item in strs.split('/'):
ind = indexes_act[item][0]
indexes_act[item].popleft()
if ind > prev:
yield ind
else:
raise ValueError("Invalid string")
prev = ind
演示:
>>> p1 = '/foo/baz/myfile.txt'
>>> p2 = '/bar/foo/myfile.txt'
>>> actual = '/foo/bar/baz/myfile.txt'
>>> list(match(p1, actual))
[0, 1, 3, 4]
>>> list(match(p2, actual))
...
raise ValueError("Invalid string")
ValueError: Invalid string
>>> p1 = '/foo/bar/bar/myfile.txt'
>>> p2 = '/bar/bar/baz/myfile.txt'
>>> actual = '/foo/bar/baz/bar/myfile.txt'
>>> list(match(p1, actual))
[0, 1, 2, 4, 5]
>>> list(match(p2, actual))
...
raise ValueError("Invalid string")
ValueError: Invalid string