![](/img/trans.png)
[英]Find index of element in sublist that is same across all the sublists in a nested list
[英]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.product
、 next
、 set.issuperset
、 map
和len
:
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
,并且 - 对于每个 - 收集list1
和list2
的笛卡尔积的下一个最佳对,该组是该组的超集- 如果它存在。
请注意,这是非常高效的product
,并且map
创建惰性迭代器并在第next
命中时提前中断,因此不会过度生成对。
你可以这样做
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.