簡體   English   中英

如何將子列表的分數分配給單詞並創建新詞典

[英]how to assign the score of the sublist to the words and to create a new dictionary

我有一個字典 adict:

a={"good":2, "bad":-2}

帶有字符串 b 子列表的列表:

b=[["how", "are", "good"],["bad", "BAD", "hello"]]

和一個整數列表,它與列表 b 的長度相同,並且是 b 的每個子列表的分數:

c=[2, -4] 

我需要將子列表的分數分配給 b 中沒有出現在 a 的鍵中的單詞它應該創建一個新字典,如下所示:

{{"how":2, "are":2},{"hello":-4}}

我已經嘗試了以下代碼,但它不起作用:

for sublst in b:
    for i in sublst:
        if i.lower() not in a.keys():
            newdict=dict(zip(sublst, c))
a={"good":2, "bad":-2} 
b=[["how", "are", "good"],["bad", "BAD", "hello"]]
c=[2, -4]

new_list = []
for i in range(len(b)):
    value = c[i]
    d= {}
    for word in b[i]:
        if(word.lower() not in a.keys()):
            d[word] = value
    new_list.append(d.copy())

print(new_list)

輸出:

 [{'how': 2, 'are': 2}, {'hello': -4}]

這是使用字典理解的一種方法。 請注意,字典是不可散列的,因此您不能擁有一組字典。 你可以得到一個字典列表,而不是如下:

k = a.keys()
[{w:s for w in l if w.lower() not in k} for l,s in zip(b,c)]
# [{'how': 2, 'are': 2}, {'hello': -4}]

您的代碼在高空滑索處出錯。 首先,

sublist = [['how', 'are', 'good']
           ['bad', 'BAD', 'hello']]

盡管

c = [2, -4]

(sublist, c) 適用於前兩個元素,而不適用於滿足條件的元素。 為了完成這項工作,必須制作一個不同的列表,包括

[['how', 'are'], ['hello']]

但這無法壓縮值,因為 zip 不適用於列表列表。 所以這個問題的解決方案就是存儲b的第i個元素的c[i]值。 如果任何子元素滿足條件,則更新字典,否則繼續迭代並更改 c[i] 的值。 該方法實現如下:-

dic = {}
for i in range(len(b)):
    score = c[i]
    for j in b[i]:
        if j.lower() not in a.keys():
            dic.update({j : score})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM