繁体   English   中英

查找 2 个元素是否在同一个子列表中

[英]Find if 2 element are in the same sublist

我有2个单词列表,

list1 = ['hello', 'world']
list2 = ['hi']

和一个子列表,如

GROUPS = [['hello','good'], ['hello', 'hi', 'etc'], ['hi', 'world', 't']]

查找 list1 和 list2 的每两个单词是否在子列表中的最快(或最少代码)方法是什么? 找到并计算它们。

我使用了这个,但如果它存在,我正在寻找更好的方法:

found = 0
list_couples = []
for a in list1:
    for b in list2:
        for gr in GROUPS:
            if a in gr and b in gr:
                found += 1
                list_couples.append((a, b))
                break

我想found = 2和一对[('hello','hi'), ('world', hi')]

最短的可能如下,使用itertools.productnextset.issupersetmaplen

from itertools import product

couples = []
for gr in map(set, GROUPS):  # make sets for O(1) contains-check
    pair = next((p for  p in product(list1, list2) if gr.issuperset(p)), None)
    if pair:
        couples.append(p)
found = len(couples)

这将迭代set -cast groups ,并且 - 对于每个 - 收集list1list2的笛卡尔下一个最佳对,该组是该组的超集- 如果它存在。

请注意,这是非常高效的product ,并且map创建惰性迭代器并在第next命中时提前中断,因此不会过度生成对。

您可以对itertools模块中的product使用列表推导:

from itertools import product

list_couples = []

for gr in GROUPS:
    list_couples.extend([(x[0], x[1]) for x in product(list1, list2) if x[0] in gr and x[1] in gr])
found = len(list_couples)

你可以这样做

from itertools import product

list1 = ['hello', 'world']
list2 = ['hi']
GROUPS = [['hello','good'], ['hello', 'hi', 'etc'], ['hi', 'world', 't']]
result = [i for i in product(list1, list2) if list(filter(lambda x: i[0] in x and i[1] in x ,GROUPS))]
found = len(result)

这将检查 list1 和 list2 中的所有选项是否存在于 GROUPS 列表之一中。

暂无
暂无

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

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