这是一个丑陋的代码,用于找到将句点分成 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 中的函数组合
生成切割点的所有组合:
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 - 如何在python中设置多个循环 'for'作为函数的参数来找到将一个句点切成n份的所有可能性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74719718/