python - 加入最多字符限制的句子列表
问题描述
我有一个列表,其中每个项目都是一个句子。只要新的组合项目不超过字符限制,我就想加入这些项目。
您可以很容易地加入列表中的项目。
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.']
你也许可以像这里一样做一个列表理解。或者我可以像这里一样做一个条件迭代器。但是我遇到了句子被截断的问题。
澄清
- 最大字符限制是指列表中单个项目的长度......而不是整个列表的长度。合并列表项时,新列表中的任何一项都不能超过限制。
- 无法合并的项目将在列表中返回,因为它们未更改。
- 将句子组合在一起,只要它们不超过限制。如果它们超出限制,请不要合并并保持原样。仅组合列表中顺序相邻的句子。
- 请确保您的解决方案满足上述输出结果:
['Alice went to the market. She bought an apple.','And she then went to the park.']
解决方案
这是一个单线解决方案,只是因为它是可能的。
[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]
不过,我怀疑这在任何实际情况下都会比显式循环更有效!
推荐阅读
- sql-server - 算术溢出:“将数字转换为数据类型数字”错误
- flutter - 如何影响单个 TimerButton 以在具有多个 TimerButton 的列表构建器中重新发送 OTP?
- node.js - AutoDesk forge 查看器 Api 集成问题
- flutter - 录制方形视频 - Flutter
- android - 如何像 NavigationAdvancedSample 一样防止底部导航栏中的片段分离?
- php - PHP类中的双花括号-如何使用它们从2个字符串生成随机字符串并返回值?
- c++ - 为模拟目的从 Chrono 实时加速
- django - 当我将 HTML 网站更改为 Django 重定向应用程序时,如何自动执行 301 重定向以将流量从旧链接转移到新链接?
- python - 如何过滤带有索引的列表
- regex - 如何将 *.htm *,htm *,html 重定向到 .htaccess 中的 *.html