首页 > 解决方案 > 用Python中的一个对象替换数组中的空对象

问题描述

我有这个数组:

["first line","","second line","","","","","more text","","","","last line"]

很难描述,所以我只想展示我想要的输出:

["first line","","second line","...","more text","...","last line"]

当数组中有 3 个或更多空对象时,应将它们替换为一个“...”。什么是最简单的方法,我可以做到这一点?

标签: pythonarrays

解决方案


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']

推荐阅读