假设我有一个列表,管道表示层次结构。
l = ['animals|fish|salmon', 'fish|salmon', 'fish', 'animals', 'furniture',
'animals|big cats|lions', 'animals|birds|fisher bird']
我想返回一个包含所有非冗余条目的列表:
l = ['animals|fish|salmon', 'animals|big cats|lions',
'animals|birds|fisher bird', 'furniture']
我尝试了按长度对列表进行排序的各种变体,然后使用“any”关键字查找其中一个条目中包含的元素。
l2 = paths.sort(key=len)
for i in l2:
if any(i in j for j in l if i != j):
...
但这并不是真的成功。谁能推荐一种更好的方法来解决这个问题?
谢谢!
最佳答案
我不确定这是否是您要找的:
l = ['animals|fish|salmon', 'fish|salmon', 'fish', 'animals', 'furniture',
'animals|big cats|lions', 'animals|birds|fisher bird']
def simplify (data):
data = ['|{}|'.format (e) for e in data]
return [e [1:-1] for e in data if all (e is other or e not in other for other in data) ]
print (simplify (l) )
它打印:
['animals|fish|salmon', 'furniture', 'animals|big cats|lions', 'animals|birds|fisher bird']
我的工作:
第一步:在每个项目的开头和结尾放置管道 '|{}|'.format
(以避免与例如 fish
和 fisher 发生冲突鸟
。
第二步:过滤列表,丢弃所有属于另一个(e not in other
)子路径的项,除了它们自身(e is other or
)。我还再次修剪额外的管道 (e [1:-1]
)
关于python - 识别列表中字符串中出现的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22869180/