Python: 如何连接列表中组合长度小于阈值的相邻字符串?
Python: How to concatenate adjacent strings in list having combined length less than threshold?
我想 merge/concatenate 列表中的相邻字符串,其组合长度低于阈值。连接的字符串应该有一个单独的 space 分隔各个字符串。
例如,如果列表包含以下字符串:
list = ['This', 'is', 'a', 'sample', 'example']
并且阈值是10,那么列表应该修改为:
list = ['This is a', 'sample', 'example']
编辑:我正在使用 for 循环比较相邻的字符串。
for i in range(1, len(list)):
if len(list[i]) + len(list[i-1]) < 10:
list[i-1] = list[i-1]+' '+list[i]
del list[i]
但这给出了IndexError: list index out of range
,因为循环计数器已经初始化为初始的len(list)
。
一种(有点懒)的方法是使用标准库中的 textwrap
模块:
>> import textwrap
>> textwrap.wrap('This is a sample example', width=10)
['This is a', 'sample', 'example']
(如果您的文本已经被拆分成单词,您必须先将其重新加入,这有点浪费,但仍然有效。)
import re
import textwrap
sample = ['This', 'is', 'a', 'sample', 'example', 'stringbiggerthan10', 'otherstring']
sample_join = " ".join(sample)
textwrap.wrap(sample_join, width=10, break_long_words=False)
['This is a', 'sample', 'example', 'stringbiggerthan10', 'otherstring']
我想 merge/concatenate 列表中的相邻字符串,其组合长度低于阈值。连接的字符串应该有一个单独的 space 分隔各个字符串。
例如,如果列表包含以下字符串:
list = ['This', 'is', 'a', 'sample', 'example']
并且阈值是10,那么列表应该修改为:
list = ['This is a', 'sample', 'example']
编辑:我正在使用 for 循环比较相邻的字符串。
for i in range(1, len(list)):
if len(list[i]) + len(list[i-1]) < 10:
list[i-1] = list[i-1]+' '+list[i]
del list[i]
但这给出了IndexError: list index out of range
,因为循环计数器已经初始化为初始的len(list)
。
一种(有点懒)的方法是使用标准库中的 textwrap
模块:
>> import textwrap
>> textwrap.wrap('This is a sample example', width=10)
['This is a', 'sample', 'example']
(如果您的文本已经被拆分成单词,您必须先将其重新加入,这有点浪费,但仍然有效。)
import re
import textwrap
sample = ['This', 'is', 'a', 'sample', 'example', 'stringbiggerthan10', 'otherstring']
sample_join = " ".join(sample)
textwrap.wrap(sample_join, width=10, break_long_words=False)
['This is a', 'sample', 'example', 'stringbiggerthan10', 'otherstring']