我试图找到所有的列表切片,其中包括一个特定的项目。假设我有一个由五个语素组成的列表w,其中之一是词干stem,我希望找到包含它的每一个可能的片段。下面是我为此编写的代码:
stem = 'stm'
w = ['a', 'b', stem, 'c', 'd']
w2 = w
stem_index = w.index(stem)
stem_slice1 = w[stem_index:]
stem_slice2 = w[:stem_index + 1]
slices = []
while len(w) > 0:
    w = w[:-1] # chops the last item
    if stem in w and w not in slices:
        slices.append(w)
    w_ = w[1:] # then chops the first item
    if stem in w_ and w_ not in slices:
        slices.append(w_)
    w2 = w2[1:] # chops the first item
    if stem in w2 and w2 not in slices:
        slices.append(w2)
    w2_ = w2[:-1] # then chops the last item
    if stem in w2_ and w2_ not in slices:
        slices.append(w2_)
while len(stem_slice1) > 0:
    stem_slice1 = stem_slice1[:-1]
    if stem in stem_slice1 and stem_slice1 not in slices:
        slices.append(stem_slice1)
while len(stem_slice2) > 0:
    stem_slice2 = stem_slice2[1:]
    if stem in stem_slice2 and stem_slice2 not in slices:
        slices.append(stem_slice2)
print (slices)运行时,此代码打印:
[['a', 'b', 'stm', 'c'], ['b', 'stm', 'c'], ['b', 'stm', 'c', 'd'], ['a', 'b', 'stm'], ['b', 'stm'], ['stm', 'c', 'd'], ['stm', 'c'], ['stm']]这似乎很好,但我想知道是否有更多的毕达通的方式来做同样的事情。
发布于 2017-12-21 20:51:19
只要得到所有有效的开始和结束指数的笛卡尔乘积,就可以做到这一点。换句话说,两个for循环就足够了。
stem = 'stm'
w = ['a', 'b', stem, 'c', 'd']
idx = w.index(stem)
slices = []
for start in range(idx+1):
    for end in range(idx+1, len(w)+1):
        slices.append(w[start:end])
print(slices)结果:
[['a', 'b', 'stm'], ['a', 'b', 'stm', 'c'], ['a', 'b', 'stm', 'c', 'd'], ['b', 'stm'], ['b', 'stm', 'c'], ['b', 'stm', 'c', 'd'], ['stm'], ['stm', 'c'], ['stm', 'c', 'd']]https://stackoverflow.com/questions/47932493
复制相似问题