我有一个字符串列表。字符串相当长。我想删除前 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/