首页 > 解决方案 > 加入最多字符限制的句子列表

问题描述

我有一个列表,其中每个项目都是一个句子。只要新的组合项目不超过字符限制,我就想加入这些项目。

您可以很容易地加入列表中的项目。

x = ['Alice went to the market.', 'She bought an apple.', 'And she then went to the park.']
' '.join(x)
>>> 'Alice went to the market. She bought an apple. And she then went to the park.'

现在说我想按顺序加入项目,只要新组合的项目不超过 50 个字符

结果将是:

['Alice went to the market. She bought an apple.','And she then went to the park.']

你也许可以像这里一样做一个列表理解。或者我可以像这里一样做一个条件迭代器。但是我遇到了句子被截断的问题。

澄清

标签: python

解决方案


这是一个单线解决方案,只是因为它是可能的。

[x[i] for i in range(len(x)) if [sum(list(map(len,x))[:j+1]) for j in range(len(x))][i] < 50]

这同样更有效 - 使用中间结果来节省重新计算 - 但仍然没有显式循环。

lens = list(map(len, x)) 
sums = [sum(lens[:i]) for i in range(len(x))]
[x[i] for i in range(len(x)) if sums < 50]

不过,我怀疑这在任何实际情况下都会比显式循环更有效!


推荐阅读