亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

python中兩個列表中的精確字符串匹配

python中兩個列表中的精確字符串匹配

冉冉說 2023-07-11 14:14:08
我需要匹配兩個列表,一個與字符,另一個與單詞我當前的代碼是:char_list=['G','UH','D','S', 'ER', 'M', 'AY', 'S', 'EH', 'L', 'F', 'B', 'AE', 'NG', 'K']word_list=['GUHD','MAORNIHNG','SER','MAY','SEHLF','BAENGK']for word_p in word_list:    scores = {}    p_s=""    if str(word_p) != "NULL":        print(word_p)        for j in char_list:            if len(word_p) == len(p_s):                print("word end")                for i in scores.keys():                    char_list.remove(i)                break            else:                if j in word_p:                    p_s=p_s+j                    scores[j] = gop_scores.get(str(j))#this returns an integer value corresponding to char         sep_scores[str(word_p)] = scores print(sep_scores)當前輸出為:-*{'GUHD': {'G': 100.0, 'UH': 18.142809657631524, 'D': 61.62375099467158}, 'MAORNIHNG': {'M': 100.0, 'NG': 43.40719714138942}, 'SER': {'S': 100.0, 'ER': 100.0}, 'MAY': {'M': 100.0, 'AY': 100.0}, 'SEHLF': {'S': 100.0, 'EH': 89.72295878282416, 'L': 100.0, 'F': 0.0}, 'BAENGK': {'B': 7.166608749080874, 'AE': 68.10287800038276, 'NG': 43.40719714138942, 'K': 100.0}}}*筆記一切看起來都很好,但 MAORNIHNG 沒有完全匹配的字符,但我仍然得到{'M','NG'},我希望 MAORNIHNG 值為空預期產出*{'GUHD': {'G': 100.0, 'UH': 18.142809657631524, 'D': 61.62375099467158}, 'MAORNIHNG': {}, 'SER': {'S': 100.0, 'ER': 100.0}, 'MAY': {'M': 100.0, 'AY': 100.0}, 'SEHLF': {'S': 100.0, 'EH': 89.72295878282416, 'L': 100.0, 'F': 0.0}, 'BAENGK': {'B': 7.166608749080874, 'AE': 68.10287800038276, 'NG': 43.40719714138942, 'K': 100.0}}}*“MAORNIHNG”值應該是空字典
查看完整描述

1 回答

?
MMTTMM

TA貢獻1869條經驗 獲得超4個贊

您只需要確保字典鍵構成整個單詞,如果不返回空字典,您可以通過連接它們并比較來做到這一點:


char_list=['G','UH','D','S', 'ER', 'M', 'AY', 'S', 'EH', 'L', 'F', 'B', 'AE', 'NG', 'K']

word_list=['GUHD','MAORNIHNG','SER','MAY','SEHLF','BAENGK']


sep_scores={}

for word_p in word_list:

    scores = {}

    p_s=""

    if str(word_p) != "NULL":

        print(word_p)

        for j in char_list:

            if len(word_p) == len(p_s):

                print("word end")

                for i in scores.keys():

                    char_list.remove(i)

                break

            else:

                if j in word_p:

                    p_s=p_s+j

                    scores[j] = 1#this returns an integer value corresponding to char 

                    

        if ''.join(scores.keys()) == word_p:

            sep_scores[str(word_p)] = scores 

        else:

            sep_scores[str(word_p)] = {}

print(sep_scores)


>>> {'GUHD': {'G': 1, 'UH': 1, 'D': 1}, 'MAORNIHNG': {}, 'SER': {'S': 1, 'ER': 1}, 'MAY': {'M': 1, 'AY': 1}, 'SEHLF': {'S': 1, 'EH': 1, 'L': 1, 'F': 1}, 'BAENGK': {'B': 1, 'AE': 1, 'NG': 1, 'K': 1}}



查看完整回答
反對 回復 2023-07-11
  • 1 回答
  • 0 關注
  • 208 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號