python - 删除除特定值外的多次出现?

标签 python algorithm list find-occurrences

我有一个文本行列表:textlines,它是一个字符串列表(以'\n' 结尾)。

我想删除多次出现的行,不包括那些只包含空格、换行和制表符的行。

换句话说,如果原始列表是:

textlines[0] = "First line\n"
textlines[1] = "Second line \n"
textlines[2] = "   \n"
textlines[3] = "First line\n"
textlines[4] = "   \n"

输出列表为:

textlines[0] = "First line\n"
textlines[1] = "Second line \n"
textlines[2] = "   \n"
textlines[3] = "   \n"

怎么做?

最佳答案

seen = set()
res = []
for line in textlines:
    if line not in seen:
        res.append(line)
        if not line.strip():
            seen.add(line)
textlines = res

关于python - 删除除特定值外的多次出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20459075/

相关文章:

python - Tensorflow如何管理图?

python - 多处理不使用所有内核

string - 如何检测字符串中的回文循环长度?

algorithm - 如何最有效地分配房间?

python - 用Python编码有向图的 bool 邻接矩阵

python - 选择文件后 Tkinter 照片没有变化

algorithm - 困惑是用 theta 表示法还是 Big Oh 表示法来表达时间复杂度

python - 将列表的列表转换为字典

python - 从列表构造一个字典,其中每个值将包含当前键的补码

python - 在python中将unicode UTF-16数据写入文件时出现问题