首页 > 解决方案 > 需要一个矩阵,使得每个元素中的字符数不超过 5K

问题描述

我有字符串列表 list1 = ['There', 'are two', 'goats on the bridge']

我需要找到一种方法,使得每次字符串中的字符数不超过 10 个。如果是这样,我需要打破它。

list2 = ['那里','有两个','山羊在','桥']。所以这应该在 10 左右或大约 10 左右,这有点像 readlines 所做的。

谢谢-Megha

标签: python-3.xlistmatrixslice

解决方案


下面简单地将每个元素拆分为不超过 k = 10 chars 的子元素

k = 10
[x[i:i+k] for x in list1 for i in range(0, len(x), k)]

结果:

['There', 'are two', 'goats on t', 'he bridge']



如果您想将空格拆分为 k = 10 plus/minus t = 2 characters,则需要一种稍微复杂的方法:

from functools import reduce
import operator

def split_about_k(s, k=10, t=1):
    """split s at spaces into k +/- t sized subtsrings"""
    i = 0
    while i < len(s)-k:
        j = s.rfind(' ', i+k-t, i+k+t)
        if j < 0:
            yield s[i:i+k]
            i = i + k
        else:
            yield s[i:j]
            i = j + 1
    yield s[i:]


reduce(operator.concat, [list(split_about_k(x, 10, 2)) for x in list1])

结果:

['There', 'are two', 'goats on', 'the bridge']

推荐阅读