作爲一個備選答案,你可以用itertools
模塊做到這一點,利用groupby
功能分組列表,也我使用combination
爲分組鍵創建一對索引列表:(i<=word.index(x)<=j
),最後使用set
獲取唯一列表。
另外請注意,您可以通過這種方法,當你有對像(i1,j1) and (i2,j2)
如果i1==0 and j2==3
和j1==i2
像(0,2) and (2,3)
這意味着這些切片結果是相同的,你需要刪除其中的一個在第一次拿到的配對索引的獨特組合。
所有在一個列表理解:
subs=[[''.join(i) for i in j] for j in [[list(g) for k,g in groupby(word,lambda x: i<=word.index(x)<=j)] for i,j in list(combinations(range(len(word)),2))]]
set([' '.join(j) for j in subs]) # set(['WIN E', 'W IN E', 'W INE', 'WI NE', 'WINE'])
演示在細節:
>>> cl=list(combinations(range(len(word)),2))
>>> cl
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
>>> new_l=[[list(g) for k,g in groupby(word,lambda x: i<=word.index(x)<=j)] for i,j in cl]
>>> new_l
[[['W', 'I'], ['N', 'E']], [['W', 'I', 'N'], ['E']], [['W', 'I', 'N', 'E']], [['W'], ['I', 'N'], ['E']], [['W'], ['I', 'N', 'E']], [['W', 'I'], ['N', 'E']]]
>>> last=[[''.join(i) for i in j] for j in new_l]
>>> last
[['WI', 'NE'], ['WIN', 'E'], ['WINE'], ['W', 'IN', 'E'], ['W', 'INE'], ['WI', 'NE']]
>>> set([' '.join(j) for j in last])
set(['WIN E', 'W IN E', 'W INE', 'WI NE', 'WINE'])
>>> for i in set([' '.join(j) for j in last]):
... print i
...
WIN E
W IN E
W INE
WI NE
WINE
>>>
你需要排列嗎?或只是子字符串? – 2014-11-06 23:35:55
只是子串,因爲它們需要是順序的。 – 2014-11-06 23:39:06
是不是你正在尋找只是「酒」與每個可能的位置內的空間? – Stuart 2014-11-06 23:43:58