python-3.x - 需要一个矩阵,使得每个元素中的字符数不超过 5K
问题描述
我有字符串列表 list1 = ['There', 'are two', 'goats on the bridge']
我需要找到一种方法,使得每次字符串中的字符数不超过 10 个。如果是这样,我需要打破它。
list2 = ['那里','有两个','山羊在','桥']。所以这应该在 10 左右或大约 10 左右,这有点像 readlines 所做的。
谢谢-Megha
解决方案
下面简单地将每个元素拆分为不超过 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']
推荐阅读
- performance - 冻结时停止 NetLogo
- bash - 为什么我的 makefile 变量在使用“define”指令时不起作用?
- javascript - 如何让 ons-navigator 与 Vue.js 一起工作?
- python - 将公式转换为cnf python
- javafx - 暂停和播放媒体播放器JavaFX中的模数问题
- graph-algorithm - Dijkstra 算法的准确性如何?
- java - OnEditorActionListener 不适用于多行 EditText
- python - 简单的弹跳计算出错
- authentication - Keycloak 对没有角色的用户进行身份验证
- python - 基于不同列 pandas 的输入值