我有一个字符串列表:mylist = ["Hanks", "Tom Hanks","Tom","Tom Can"]
,我需要删除列表中是另一个字符串的子字符串的较短字符串。
例如,在上面的情况下,输出应为:["Tom Hanks","Tom Can"]
。
我在Python中做了什么:
mylist = ["Hanks", "Tom Hanks","Tom","Tom Can"]
newlst = []
for x in mylist:
noexist = True
for j in mylist:
if x==j:continue
noexist = noexist and not(x in j)
if (noexist==True):
newlst.append(x)
print(newlst)
代码运行正常。我该如何使其更高效?
noexist
为假,您就可以停止将其与列表的剩余部分进行比较,因此在内部循环中加入if not noexist: break
将带来一些好处。不确定是否还有更多可以改进。 - Tadhg McDonald-Jensen