我很想过滤字符串的名单如下方式:我要排除的字符串,如果没有至少在同一个列表中的一个其他字符串,它是“在”它。或以不同的方式把这个:我想保持的字符串,如果是同一列表的任何其他字符串中它。如果可能的话,区分大小写应该在这里发挥作用。
为了更清楚一点,请在下面的示例中找到:
我的“第一”列表包含每个字符串:
elements =["tree","TREE","treeforest","water","waterfall"]
应用解决方案后,我希望收到以下列表:
elements = ["tree","TREE","water"]
例如:tree
在中treeforest
。因此,treeforest
被排除在我的清单之外。这同样适用于water
和waterfall
。然而tree
,TREE
并water
应保持,因为没有其他的字符串,是“在”他们。
正如我想将其应用于“更大的”字符串列表中一样,更有效的解决方案是首选。
希望这是可以理解的。在此先多谢!!非常感谢您的帮助。
具有2个循环的相当优化的功能,可节省许多循环迭代:
def filterlist(l):
# keep track of elements, which will be deleted
deletelist = [False for _ in l]
for i, el in enumerate(l):
# already in deletelist, jump right to the next el
if deletelist[i]:
continue
for j, el2 in enumerate(l):
# comparing item to itself or el2 already in deletelist?
# jump to next el2
if i == j or deletelist[j]:
continue
# the comparison everyone expects
if el in el2:
deletelist[j] = True
# also, check the other way around
# will save loop iterations later
elif el2 in el:
deletelist[i] = True
break # causes jump to next el
# create new list, keep elements that are not in deletelist
return [el for i, el in enumerate(l) if not deletelist[i]]
通常内置函数的速度更快,因此让我们将其与Ed Ward的解决方案进行比较:
# result of Ed Ward's solution using timeit:
100000 loops, best of 10: 5.38 usec per loop
# filterlist function with loops using timeit:
100000 loops, best of 10: 4.42 usec per loop
有趣,但是要获得真正具有代表性的结果,您应该使用较大的元素列表运行timeit。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句