繁体   English   中英

查找另一个列表中每个子列表的超集索引

[英]Find the index of supersets for each sublist in another list

我试图在与另一个列表中的元素共享相同数据的元素列表中找到索引号。 这些是我的清单:

list_A = [['A',1,'a',],['B',2,'b'],['C',3,'c'],['D',4,'d'],['E',5,'e'],['F',6,'f']]
list_B = [['A','a'],['D','d']['E','e']]

所需的输出应为:

[0,3,4]

我已经尝试过使用set()交集和index函数,但是无法使“ set”与列表结合使用。

如果列表值没有重复项,则可以将所有内容都转换为集合,并在列表推导内执行子集检查。

set_A = list(map(set, list_A))
set_B = list(map(set, list_B)) 
# set_B = map(set, list_B) # If you intend to use and throw. 

[next((i for i, a in enumerate(set_A) if a.issuperset(b)), None) for b in set_B]
# [0, 3, 4]

现在,如果没有匹配项,则next返回您传递给它的默认值,在这种情况下为None

您可以执行以下操作:

list_A = [['A', 1, 'a', ], ['B', 2, 'b'], ['C', 3, 'c'], ['D', 4, 'd'], ['E', 5, 'e'], ['F', 6, 'f']]
list_B = [['A', 'a'], ['D', 'd'], ['E', 'e']]

set_B = list(map(set, list_B))
result = [i for i, e in enumerate(list_A) if any(b.intersection(e) for b in set_B)]

print(result)

输出量

[0, 3, 4]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM