【发布时间】:2017-12-21 20:45:14
【问题描述】:
我正在尝试查找包含特定项目的所有列表切片。
假设我有一个由五个词素组成的列表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']]
它似乎工作正常,但我想知道是否有更 Pythonic 的方式来做同样的事情。
【问题讨论】:
-
可能有多个 stem 实例,其中任何一个都意味着您想要 subslice?
-
我假设词干已经被指定为词干,所以只有一个词干。
-
将切片设为一组,然后去掉所有的“not in”子句。
-
集合不包含列表。我会得到错误:unhashable type: 'list'。
标签: python python-3.x list slice