python - 用Python中的一个对象替换数组中的空对象
问题描述
我有这个数组:
["first line","","second line","","","","","more text","","","","last line"]
很难描述,所以我只想展示我想要的输出:
["first line","","second line","...","more text","...","last line"]
当数组中有 3 个或更多空对象时,应将它们替换为一个“...”。什么是最简单的方法,我可以做到这一点?
解决方案
itertools.groupby
很自然地适合这个。只需在理解中进行您想要的测试:
from itertools import groupby
l = ["first line","","second line","","","","","more text","","","","last line"]
['...' if k=='' and len(list(g)) >= 3 else k for k, g in groupby(l)]
# ['first line', '', 'second line', '...', 'more text', '...', 'last line']
编辑:
如果没有重复其他内容,上面的内容很好,但它会折叠你想要保留的重复元素。这是一种稍微复杂的方法,可以避免这种情况:
from itertools import groupby
# we want both "first line" strings in the output
l = ["first line","first line", "","second line","","","","","more text","","","","last line"]
def removeEmpties(l):
for k, g in groupby(l):
group = list(g)
if k == '' and len(group) >= 3:
yield '...'
else:
yield from group
list(removeEmpties(l))
# ['first line', 'first line', '', 'second line', '...', 'more text', '...', 'last line']
推荐阅读
- rust - 为什么转移所有权后可以使用非捕获闭包?
- react-native - 如何在博览会中从服务器设置正确的图像路径并做出本机反应
- php - 如何获取消息返回 AJAX PHP JSON
- angular - 如何在不使用 XPath 的情况下读取 Protractor 表中的特定行?
- django - 使用下拉菜单测试我的网站时的 Django 问题
- php - 根据用户的id将用户重定向到不同的页面
- python - python3中的lxml问题
- amazon-web-services - 减小 EBS 根卷的大小 - Windows
- batch-file - 如何使用正则表达式使用批处理脚本搜索和替换文本
- javascript - 如何将导航添加到屏幕而不显示在抽屉中