【问题标题】:How do I remove all elements from a list which is a subsequence of another bigger element in the same list in python?如何从列表中删除所有元素,该列表是python中同一列表中另一个更大元素的子序列?
【发布时间】:2021-06-21 23:41:53
【问题描述】:

我有一个如下所示的列表:

[['rest'],['look'],['rest','look'],['resting','look],['apple','mango'],['apple', 'man'],['apple','banana','mango'],['rest','resting','look','looked','it','spit']]

必须删除作为另一个元素的子字符串/子序列的所有元素。例如元素['rest'] 和['look'] 已经存在于列表元素['rest','look'] 和['rest','resting','look','looked','it','spit'] 中,因此必须从最终列表中删除它们。此外,元素['rest','look'] 是 ['rest','resting','look','looked','it','spit'], so it should be removed. Similarly, ['resting','look']is a substring of[ 'rest','resting','look','looked','it','spit']`,所以它也必须被删除。元素 ['apple','mango'] 因为它是['apple','banana','mango'] 应该被删除,但 ['apple','man'] 不应该被删除,因为它不是一个常见的子序列。输出必须是一个列表而不是一个集合。

我试过了:

x = [['rest'],['look'],['rest','look'],['resting','look'],['apple','mango'],['apple','man'],['apple','banana','mango'],['rest', 'resting', 'look', 'looked', 'it', 'spit']]

res=[]

found=0

for i in x:
   for item in i:
     for j in x:
          for item1 in j:
            if item == item1:
               found=1
     if found==0:
          res.append(item)

print res

我得到的输出是一个空列表。所需的输出是:

[['apple','man'],['apple','banana','mango'],['rest','resting','look','looked','it','spit']]

【问题讨论】:

  • 您可以简单地将list 展平并将其转换为set,这样就可以了。
  • 如果我的回答解决了,请接受并投票。

标签: python nested-lists


【解决方案1】:

您可以改为使用集合推导,将列表展平为集合。

x = [['rest'],['look'],['rest','look'],['resting','look'],['rest', 'resting', 'look', 'looked', 'it', 'spit']]
In [2]: results = {s_ for s in x for s_ in s}
In [2]: results
Out[3]: {'it', 'look', 'looked', 'rest', 'resting', 'spit'}

【讨论】:

    【解决方案2】:

    我认为这就是您尝试实施的内容。我认为您不需要变量found,您只需检查子列表中的每个项目(例如,['rest', 'look'] 已经追加到res。

    x = [['rest'], ['look'], ['rest', 'look'], ['resting', 'look'], ['rest', 'resting', 'look', 'looked', 'it', 'spit']]
    res = []
    for L in x:
        for item in L:
            if item not in res:
                res.append(item)
    
    
    print(res)
    # ['rest', 'look', 'resting', 'looked', 'it', 'spit']
    

    【讨论】:

      猜你喜欢
      • 2022-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多