【问题标题】:remove sublist from a single list of list python从列表 python 的单个列表中删除子列表
【发布时间】:2023-03-26 02:41:01
【问题描述】:

我已经使用了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']]

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

**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']]

我已尝试使用以下代码:

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)]

【问题讨论】:

  • 列表中的每个列表都是子列表。您要删除的依据是什么。
  • 是的@PySaad,我认为我们必须从输出中找出模式并删除它们
  • @pc_pyr py 的要求是,您要在什么基础上删除一些列表并保留一些。需要删除的列表有什么特点?

标签: python list subset


【解决方案1】:

你必须用, 拆分所有子列表中的元素,而不是使用你已经找到的solution

st = [{i for e in l for i in e.split(',') } for l in list1]
[l for l, s in zip(list1, st) if not any(s < other for other in st)]

输出:

[['A,B,C,D', 'Y', 'hello'],
 ['A,B,C', 'Z', 'hello'],
 ['H,I,J,K,L', 'Z', 'hello'],
 ['A,D,C,B', 'Z', 'hi']]

【讨论】:

  • 感谢@kederrac,它与模式完美配合,请澄清一下,当我在列表列表中添加[['E,F,G,H','T','welcome'],['A,E,H','T','welcome']] 时,除了上述逻辑之外,我只想选择 [' E,F,G,H','T','welcome'] 并删除 ['A,E,H','T','welcome']] 因为 'E,H' 已经存在于 ['E ,F,G,H','T','欢迎']。有没有办法实现它..
猜你喜欢
  • 2020-10-06
  • 1970-01-01
  • 2018-04-22
  • 2020-01-23
  • 1970-01-01
  • 1970-01-01
  • 2022-12-20
  • 1970-01-01
相关资源
最近更新 更多