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/

相关文章:

java - 了解大 O 符号 - 破解编码面试

php - 生成唯一 key 的简单算法

python - 在 python 中,从字典列表中删除列表的好方法

ruby-on-rails - Rails - 通过连接表以逗号分隔的列表

python - 为什么在执行 python 脚本时会出现 No such file or directory 错误?

python - 使用Python和BeautifulSoup访问网页标签的title属性

python - Windows 10 - python pip 不工作(添加了环境变量)

c++ - 存储和检索相应的项目

c++ - 如何将默认迭代器写入通用列表?

python - 涉及 float 、整数和 sqlite 的奇怪 Python 行为