【问题标题】:remove elements from a single list of list python based on pattern-mathing基于模式匹配从列表 python 的单个列表中删除元素
【发布时间】:2020-03-11 08:14:16
【问题描述】:

我访问过Removing sublists from a list of lists,但是当我为我的数据集扩展它时,它对我的​​情况不起作用。因此发布了一个新问题。

list1=[['A,C,D', 'Y', 'hello'],
['A,B,D', 'Y', 'hello'],
['B,C,D', 'Y', 'hello'],
['A,B,C,D', 'Y', 'hello'],
['A', 'Z', 'hello'],
['A,C', 'Z', 'hello'],
['B,C', 'Z', 'hello'],
['A,C', 'Z', 'hello'],
['A,B,C', 'Z', 'hello'],
['H,I,J,K', 'Z', 'hello'],
['H,K', 'Z', 'hello'],
['H,L', 'Z', 'hello'],
['I,J,K,L', 'Z', 'hello'],
['H,I,J,K,L', 'Z', 'hello'],
['B,C,D','Z','hi'],
['A,D,C,B','Z','hi'],
['E,F,G,H','T','welcome'],
['A,E,H','T','welcome']]

我想删除一些元素并在下面发布所需的输出:

**Output**
[['A,B,C,D', 'Y', 'hello'],
 ['A,B,C', 'Z', 'hello'],
 ['H,I,J,K,L', 'Z', 'hello'],
 ['A,D,C,B','Z','hi'],
 ['E,F,G,H','T','welcome']]

我已尝试使用以下代码:

sets = [set(l) for l in lists]
new_list = [l for l,s in zip(lists, sets) if not any(s < other for other in sets)]

【问题讨论】:

  • 您正在删除['A,E,H','T','welcome'],因为EH 已经在['E,F,G,H','T','welcome'] 中(来自here)但是您没有将相同的规则应用于另一个,您必须提到您对待那些与welcome 不同
  • 请解释删除条目后的逻辑。我似乎不清楚。

标签: python list subset


【解决方案1】:

查看您的输入和所需的输出,您似乎想在"," 上拆分每个列表的第一个元素。现在它们是逗号分隔的字符串,因此子集逻辑不适用于它们。所以你可以这样做:

sets = [set(l[0].split(',')) | set(l[1:]) for l in lists]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多