2010-12-07 61 views
2
的所有子樹

給出「a.b.c.d.e」我想要有效地獲得所有子樹,例如, 「b.c.d.e」和「c.d.e」,但不包括「a.d.e」或「b.c.d」。獲得值爲

現實世界的情況:

我有foo.bar.baz.example.com,我想所有可能的子域樹。

回答

5
listed = "a.b.c.d.e".split('.') 
subtrees = ['.'.join(listed[idx:]) for idx in xrange(len(listed))] 

鑑於你的樣本數據,子樹等於['a.b.c.d.e', 'b.c.d.e', 'c.d.e', 'd.e', 'e']

2
def parts(s, sep): 
    while True: 
     yield s 
     try: 
      # cut the string after the next sep 
      s = s[s.index(sep)+1:] 
     except ValueError: 
      # no `sep` left 
      break 

print list(parts("a.b.c.d.e", '.')) 
# ['a.b.c.d.e', 'b.c.d.e', 'c.d.e', 'd.e', 'e'] 
0

不確定,如果這是你想要的。

但是用不同的大小對列表進行切片會產生該結果。

>>> x = "a.b.c.d.e" 
>>> k = x.split('.') 
>>> k 
['a', 'b', 'c', 'd', 'e'] 
>>> l = [] 
>>> for el in range(len(k)): l.append(k[el+1:]) 
... 
>>> l 
[['b', 'c', 'd', 'e'], ['c', 'd', 'e'], ['d', 'e'], ['e'], []] 
>>> [".".join(l1) for l1 in l if l1] 
['b.c.d.e', 'c.d.e', 'd.e', 'e'] 
>>> 

當然,以上是舉例說明的過程。你可以將它們組合成一個班輪。

[編輯:我想答案是一樣的任何位置,並且解釋了好]

+0

我的答案出了什麼問題!有人能告訴我嗎? – pyfunc 2010-12-07 19:58:39

3
items = data.split('.') 
['.'.join(items[i:]) for i in range(0, len(items))]