且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从python中的字符串中删除重复的行

更新时间:2021-12-05 22:02:51

对于 Python 2.7+,这可以通过单行来完成:

For Python 2.7+, this can be done with a one-liner:

from collections import OrderedDict

test_string = "line1 \n line2 \n line3 \n line2 \n line2 \n line 4"

"\n".join(list(OrderedDict.fromkeys(test_string.split("\n"))))

这给了我:'line1 \n line2 \n line3 \n line 4'