![](/img/trans.png)
[英]How to compare two lists based on first element and get the matching values into dictionary?
[英]Compare two lists and get matching results in a dictionary - python
我有兩個列表,我想找到具有相同/部分字符的項目並將結果放入字典中:
list_a= ['helloyou', 'waithere', 'byenow']
list_b =[ 'wait', 'hello', 'bye']
想要的結果:
dict_c= {'helloyou:hello', 'waithere:wait', 'byenow:bye'}
我已經嘗試過了,但似乎不起作用:
dict_c= {j:i for i,j in zip(list_a,list_b) if re.match(j,i)}
編輯:
我可能有一些不一樣的項目,例如:
list_a= ['helloyou', 'waithere', 'byenow']
list_b =[ 'yeswait', 'plushello', 'nobye']
想要的結果:
dict_c= {'helloyou:plushello', 'waithere:yeswait', 'byenow:nobye'}
編輯
如果我可以改為有這樣的情況,我可以使用分隔符來拆分項目並使用開頭
list_a = ['hid/jui/helloyou', 'hhh/hdhdh/waithere', 'jcdjcjd/bdcdbc/byenow']
list_b = ['abc/efg/waitai_lp', 'hil/mno/helloai_lj', 'pqr/byeai_ki']
想要的結果
dict_c = {'hid/jui/helloyou:hil/mno/helloai_lj','hhh/hdhdh/waithere:abc/efg/waitai_lp', 'jcdjcjd/bdcdbc/byenow:pqr/byeai_ki'}
嘗試這個 -
問題是您正在zipping
2 個列表中的相應項目,而不是在它們之間進行cross-product
。 因此,在壓縮版本中,只有(bye,byenow)
會從re.match
返回一些東西。
from itertools import product
{j:i for i,j in product(list_a, list_b) if re.match(j,i)}
{'hello': 'helloyou', 'wait': 'waithere', 'bye': 'byenow'}
list_a= ['helloyou', 'waithere', 'byenow']
list_b =[ 'wait', 'hello', 'bye']
dict_c = {a:b for a in list_a for b in list_b if a.startswith(b)}
Output dict_c: {'helloyou': 'hello', 'waithere': 'wait', 'byenow': 'bye'}
您可以考慮使用此處解釋的方法,並結合@Akshay 的答案
from collections import Counter
from itertools import product
def shared_chars(s1, s2):
return sum((Counter(s1) & Counter(s2)).values())
{j:i for i,j in product(list_a, list_b) if shared_chars(j,i) > 3}
困難的部分是根據一些參數(例如正在檢查的字符串的長度)以動態方式設置常量值“3”。 目前,我認為最短的單詞“再見”是最少的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.