【问题标题】:Removing Lists that Contain Sublists删除包含子列表的列表
【发布时间】:2020-11-02 17:02:55
【问题描述】:

有没有办法从包含子列表的列表中删除列表?

假设我有从 a 到 e 的 5 个元素。

我在下面找到了从 0 号到 5 号的所有组合:

all_combinations = [[], ['a'], ['b'], ['c'], ['d'], ['e'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 
                   'e'], ['b', 'c'], ['b', 'd'], ['b', 'e'], ['c', 'd'], ['c', 'e'], ['d', 'e'], 
                   ['a', 'b', 'c'], ['a', 'b', 'd'], ['a', 'b', 'e'], ['a', 'c', 'd'], ['a', 'c',
                   'e'], ['a', 'd', 'e'], ['b', 'c', 'd'], ['b', 'c', 'e'], ['b', 'd', 'e'],                
                   ['c', 'd', 'e'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'e'], ['a', 'b', 
                   'd', 'e'], ['a', 'c', 'd', 'e'], ['b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]

现在假设我要删除其中一些包含子列表的组合:

sublists = [['a', 'c'], ['c', 'd'], ['b', 'e']]

有没有一种简单的方法可以做到这一点?我应该只留下不包含这些子列表的组合。我应该只得到 a 和 c 不在一起、c 和 d 不在一起、b 和 e 不在一起的列表。

编辑:想要得到这样的输出:

valid_combinations = [[], ['a'], ['b'], ['c'], ['d'], ['e'], ['a', 'b'], 
                     ['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'],
                     ['c', 'e'], ['d', 'e'], ['a', 'b', 'd'], 
                     ['a', 'd', 'e']]
                                    
                   

【问题讨论】:

  • [sl for sl in all_combinations if not any(set(e)>=set(sl) for e in sublists)]

标签: python list sublist


【解决方案1】:

您可以使用sets查看sublists中的完整项目列表是否包含在all_combinations的子列表中:

>>> [sl for sl in all_combinations if not any(set(e)<=set(sl) for e in sublists)]
[[], ['a'], ['b'], ['c'], ['d'], ['e'], ['a', 'b'], ['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'], ['c', 'e'], ['d', 'e'], ['a', 'b', 'd'], ['a', 'd', 'e']]

>>> _==valid_combinations
True

【讨论】:

    【解决方案2】:

    试试这个:

    result = [item for item in all_combinations if item not in sublists] 
    

    【讨论】:

    • 我相信 OP 想要排除任何包含子列表的列表,这只排除等于子列表之一的列表
    【解决方案3】:

    一种可能的方法是使用集合,特别是函数issuperset 来检查一个列表是否包含另一个列表的所有元素。因此,以下列表推导返回 all_combinations 中不包含 sublists 中任何 b 的所有元素的所有元素 a

    [a for a in all_combinations if all(not set(a).issuperset(set(b)) for b in sublists)]
    

    【讨论】:

      猜你喜欢
      • 2018-05-13
      • 1970-01-01
      • 2018-10-12
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-31
      • 2018-08-18
      相关资源
      最近更新 更多