创建一个详尽的'n`子串列表(Creating an exhaustive list of `n` substrings)

编程入门 行业动态 更新时间:2024-10-06 16:29:25
创建一个详尽的'n`子串列表(Creating an exhaustive list of `n` substrings)

我正在训练将一个字符串拆分为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 substrings

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

更多推荐

本文发布于:2023-07-27 08:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1287734.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:串列   创建一个   详尽   Creating   list

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!