我想比較嵌套串列中包含的所有串列,以在末尾有對應的配對詞。
我用 2 個不同的串列來管理它,以獲取每個串列中匹配的字串。
這樣 :
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)
2 個串列的代碼并不完美,因為我得到了重復。
uj5u.com熱心網友回復:
您可以在串列理解中嘗試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')}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/522686.html
