python - 识别列表中字符串中出现的元素

标签 python

假设我有一个列表,管道表示层次结构。

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(以避免与例如 fishfisher 发生冲突鸟

第二步:过滤列表,丢弃所有属于另一个(e not in other)子路径的项,除了它们自身(e is other or)。我还再次修剪额外的管道 (e [1:-1])

关于python - 识别列表中字符串中出现的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22869180/

相关文章:

python - dash app : how position html div? 中的布局管理

python - 在 Python 中使用 PCA 进行图像聚类和降维

python - 使用 SQLAlchemy (Python) 创建模型对象时生成 GUID

python从父包导入模块

python - "Unsparsing"具有给定掩码的 numpy 数组

python - 连接数据帧而不加倍索引

python - 选择数组的每 n 个索引

python - 在 zip 文件中使用自定义主题

python - numpy 数组中的额外小数?

python - 最好的 python 库,当用户提交时,使 textarea 在网页中安全