给出“a.b.c.d.e”我想要有效地获得所有子树,例如, “b.c.d.e”和“c.d.e”,但不包括“a.d.e”或“b.c.d”。获得值为
现实世界的情况:
我有foo.bar.baz.example.com,我想所有可能的子域树。
给出“a.b.c.d.e”我想要有效地获得所有子树,例如, “b.c.d.e”和“c.d.e”,但不包括“a.d.e”或“b.c.d”。获得值为
现实世界的情况:
我有foo.bar.baz.example.com,我想所有可能的子域树。
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']
。
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']
不确定,如果这是你想要的。
但是用不同的大小对列表进行切片会产生该结果。
>>> 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']
>>>
当然,以上是举例说明的过程。你可以将它们组合成一个班轮。
[编辑:我想答案是一样的任何位置,并且解释了好]
items = data.split('.')
['.'.join(items[i:]) for i in range(0, len(items))]
我的答案出了什么问题!有人能告诉我吗? – pyfunc 2010-12-07 19:58:39