我想比较嵌套列表中包含的所有列表,以便在末尾有对应的配对词who。
我用两个不同的列表来管理它,以获得每个列表中匹配的字符串。
这样:
listA = [['Test1','Test2','Test3'], ['Test1','Test4','Test2']]
listB = [['Test1','Test2','Test5'], ['Test10','Test4','Test2']]
我得到的结果是:
['Test1', 'Test2'] # Matched at [('Test1,'Test2'),'Test3'] -> [('Test1','Test2'),'Test5']
['Test2'] # Matched at ['Test1','Test4',('Test2')] -> ['Test1',('Test2'),'Test5']
['Test4', 'Test2'] # Matched at ['Test1',('Test4','Test2)] -> ['Test10',('Test4','Test2')]
在这个例子中,我们注意到"Test3、Test5和Test10"不在结果中,因为它们都与其他列表不匹配。
我想用一个嵌套列表来完成它。
list = [['Test1','Test2','Test3'], ['Test1','Test4','Test2'], ['Test1','Test2','Test5'], ['Test5','Test4','Test2']]
这里的代码我使用两个列表:
from collections import Counter
from itertools import takewhile, dropwhile
for x in listB:
for y in listA:
counterA = Counter(x)
counterB = Counter(y)
count = counterA + counterB
count = dict(count)
prompt_match = [k for k in count if count[k] == 2]
print(prompt_match)
这两个列表的代码并不完美,因为我有重复的列表。
您可以在列表理解中尝试set
交集
from itertools import product
listA = [['Test1','Test2','Test3'], ['Test1','Test4','Test2']]
listB = [['Test1','Test2','Test5'], ['Test10','Test4','Test2']]
set(tuple(set(x)&set(y)) for x,y in product(listA, listB))
# output
{('Test1', 'Test2'), ('Test2',), ('Test4', 'Test2')}
For nested list use below approach
from itertools import combinations
listA = [['Test1','Test2','Test3'], ['Test1','Test4','Test2'], ['Test1','Test2','Test5'], ['Test10','Test4','Test2']]
set(tuple(set(x)&set(y)) for x,y in combinations(listA, 2))
# output
{('Test1', 'Test2'), ('Test2',), ('Test4', 'Test2')}