我正在训练将一个字符串拆分为n个子串并返回它们的元组列表。
我现在使用for (w1,w2) in [(w[:i],w[i:]) for i in range(len(w))]代码for (w1,w2) in [(w[:i],w[i:]) for i in range(len(w))]其中w是包含单词的变量。 因此,如果w='house'那么这将返回[('','house'),('h','ouse')等。
这非常适合将字符串拆分成所有可能的字符串对,但现在我想进行其他分割(例如n=3 )字符串,例如'ho','u','se'将单个字符串拆分为全部n子串的可能方式。 我怎样才能有效地做到这一点?
I am training to split a string into n substrings and return a list of tuples of them.
I now use the code for (w1,w2) in [(w[:i],w[i:]) for i in range(len(w))] where w is the variable which contains the word. So if w='house' then this will return [('','house'),('h','ouse') etc..
This works perfectly for splitting a string into all possible pairs of strings, but now I want to make other splits (e.g. n=3) of strings such as 'ho','u','se' which split a single string into all possible ways of n substrings. How can I do that efficiently?
最满意答案
以下是使用生成器递归执行此操作的一种方法:
def split_str(s, n): if n == 1: yield (s,) else: for i in range(len(s)): left, right = s[:i], s[i:] for substrings in split_str(right, n - 1): yield (left,) + substrings for substrings in split_str('house', 3): print substrings打印出:
('', '', 'house') ('', 'h', 'ouse') ('', 'ho', 'use') ('', 'hou', 'se') ('', 'hous', 'e') ('h', '', 'ouse') ('h', 'o', 'use') ('h', 'ou', 'se') ('h', 'ous', 'e') ('ho', '', 'use') ('ho', 'u', 'se') ('ho', 'us', 'e') ('hou', '', 'se') ('hou', 's', 'e') ('hous', '', 'e')如果您不想要空字符串,请将循环边界更改为
for i in range(1, len(s) - n + 2):Here is one way to do this, recursively, using a generator:
def split_str(s, n): if n == 1: yield (s,) else: for i in range(len(s)): left, right = s[:i], s[i:] for substrings in split_str(right, n - 1): yield (left,) + substrings for substrings in split_str('house', 3): print substringsThis prints out:
('', '', 'house') ('', 'h', 'ouse') ('', 'ho', 'use') ('', 'hou', 'se') ('', 'hous', 'e') ('h', '', 'ouse') ('h', 'o', 'use') ('h', 'ou', 'se') ('h', 'ous', 'e') ('ho', '', 'use') ('ho', 'u', 'se') ('ho', 'us', 'e') ('hou', '', 'se') ('hou', 's', 'e') ('hous', '', 'e')If you don't want the empty strings, change the loop bounds to
for i in range(1, len(s) - n + 2):更多推荐
发布评论