python - 从列表中删除类似开头的字符串 - python

标签 python string list

我有一个字符串列表。字符串相当长。我想删除前 10 个或更多字符相同的字符串,只保留其中一个。例如:

lst = ['I am going today to London', 'I am going today to Tokyo', 'My name is name']

应该给,

lst = ['I am going today to Tokyo', 'My name is name']

可以保留任何字符串。如何有效地做到这一点?

最佳答案

使用 set 的解决方案对象:

lst = ['I am going today to London', 'I am going today to Tokyo', 'My name is name']
s10 = set()
result = []
for l in lst:
    if (l[0:10] not in s10): result.append(l)
    s10.add(l[0:10])

print(result)

输出:

['I am going today to London', 'My name is name']
<小时/>

l[0:10] not in s10 - 测试 l[0:10] 行的前 10 个字符是否为非成员 in set s10(s10 填充唯一的 10 个字符序列)

关于python - 从列表中删除类似开头的字符串 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43426945/

相关文章:

python - python 2.4的JSON模块?

python - 如何管理 Python 循环中的副作用?

python - 使用 subprocess.check_output() 在 python 中搜索文件

java - 将声音文件链接到字符串值

java - ArrayList 删除不起作用?

c# - 在 C# 中合并和更新两个列表

python - Dockerized Angular 4 和 Django 编译成功但是 localhost :4200 is not working

c# - 如何将纯文本json数据转成字符串?

python - 分隔字符串的最佳 ASCII 字符是什么?

python - 如何获取元素在列表中出现的次数 Python