Search code examples
pythonpython-3.xlistsubsetindices

Python find subsets positions


I have a very large list and want to check the subsets positions,I try this:

l = ['7', '10', '8', '8', '6', '13', '7', '10', '13', '13', 
'7', '11', '9', '7', '15', '9', '10', '13', '6', '16']

print(set(['10', '13']).issubset(set(l)))

k= []
for i in range(0, len(l) - 1):
    if l[i] == '10' and l[i + 1] == '13':
        k.append(i)

print(k) 

#True
#[7, 16]

If the list is very large, I dont think this is a Python way, so is there's better way?


Solution

  • chop a sublist, sl length slice len(sl) out of the very long list vll

    and see if they equal if sl == vll[i:i+len(sl)]

    increment i, for i in range(len(vll)-len(sl)+1)

    vll = ['7', '10', '8', '8', '6', '13', '7', '10', '10', '13', 
    '7', '11', '9', '7', '15', '9', '10', '10', '6', '16']
    
    sl = ['10', '10']
    
    [i for i in range(len(vll)-len(sl)+1) if sl == vll[i:i+len(sl)]]
    
    Out[986]: [7, 16]