这里有一个难看的代码,可以找到将句号分成5部分的所有可能性.有没有可能创建一个函数,使其看起来更好,并以切割次数为参数?

我只会写每for个循环:

part_list = pd.DataFrame(columns=['period_array'])
for i in range(1, period_size):
    for j in range(1, period_size - i):
        for h in range(1, period_size - (i + j)):
            for g in range(1, period_size - (i + j + h)):
                part_list = part_list.append({'period_array':
                                                  np.array([[0, i],
                                                            [i, i + j],
                                                            [i + j, i + j + h],
                                                            [i + j + h, i + j + h + g],
                                                            [i + j + h + g, period_size]])},
                                             ignore_index=True)

推荐答案

使用module itertools中的函数combinations生成切削点的所有组合:

from itertools import combinations, chain, pairwise

def all_cuts(seq, n):
    for comb in combinations(range(1,len(seq)), n-1):
        yield tuple(seq[i:j] for i,j in pairwise(chain((0,), comb, (len(seq),))))

print( list(all_cuts('Hello, World!', 3)) )
# [('H', 'e', 'llo, World!'), ('H', 'el', 'lo, World!'),
#  ('H', 'ell', 'o, World!'), ('H', 'ello', ', World!'),
#  ('H', 'ello,', ' World!'), ...
#                        ..., ('Hello, Wor', 'l', 'd!'),
#  ('Hello, Wor', 'ld', '!'), ('Hello, Worl', 'd', '!')]

Python相关问答推荐

如何在具有重复数据的pandas中对groupby进行总和,同时保留其他列

如何在msgraph.GraphServiceClient上进行身份验证?

时间序列分解

max_of_three使用First_select、second_select、

Polars:用氨纶的其他部分替换氨纶的部分

从一个系列创建一个Dataframe,特别是如何重命名其中的列(例如:使用NAs/NaN)

Python+线程\TrocessPoolExecutor

Python脚本使用蓝牙运行在Windows 11与raspberry pi4

Python中的变量每次增加超过1

为什么if2/if3会提供两种不同的输出?

在极中解析带有数字和SI前缀的字符串

如何在BeautifulSoup/CSS Select 器中处理regex?

如何创建引用列表并分配值的Systemrame列

Python—为什么我的代码返回一个TypeError

当输入是字典时,`pandas. concat`如何工作?

如何使用大量常量优化代码?

为什么在不先将包作为模块导入的情况下相对导入不起作用

PYODBC错误(SQL包含-26272个参数标记,但提供了235872个参数,HY 000)

生产者/消费者-Queue.get by list

使用OpenPYXL切换图表上的行/列