Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 创建“n”子字符串的详尽列表_Python_String_Split - Fatal编程技术网

Python 创建“n”子字符串的详尽列表

Python 创建“n”子字符串的详尽列表,python,string,split,Python,String,Split,我正在训练将一个字符串拆分为n个子字符串,并返回它们的元组列表 我现在使用代码 for(w1,w2)in[(w[:i],w[i:])for i in-range(len(w))其中w是包含单词的变量。因此,如果w='house'那么它将返回[('house'),('h','ouse')等 这非常适合将字符串拆分为所有可能的字符串对,但现在我想进行其他拆分(例如,n=3)将单个字符串拆分为所有可能的n子字符串的字符串,如'ho'、'u'、'se'。如何有效地执行此操作?这里有一种方法,使用生成器递

我正在训练将一个字符串拆分为n个子字符串,并返回它们的元组列表

我现在使用代码
for(w1,w2)in[(w[:i],w[i:])for i in-range(len(w))
其中
w
是包含单词的变量。因此,如果
w='house'
那么它将返回
[('house'),('h','ouse')


这非常适合将字符串拆分为所有可能的字符串对,但现在我想进行其他拆分(例如,
n=3
)将单个字符串拆分为所有可能的
n
子字符串的字符串,如
'ho'、'u'、'se'
。如何有效地执行此操作?

这里有一种方法,使用生成器递归执行此操作:

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):