简体   繁体   English

如何将子列表的分数分配给单词并创建新词典

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

I have a dictionary adict:我有一个字典 adict:

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

a list with sublist of strings b:带有字符串 b 子列表的列表:

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

and a list of integers which is the same length as list b and is a score of each sublist of b:和一个整数列表,它与列表 b 的长度相同,并且是 b 的每个子列表的分数:

c=[2, -4] 

I need to assign the score of the sublist to the words in b that do not appear i the keys of a It should create a new dictionary as follows:我需要将子列表的分数分配给 b 中没有出现在 a 的键中的单词它应该创建一个新字典,如下所示:

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

I have tried the following code but it does not work:我已经尝试了以下代码,但它不起作用:

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)

output:输出:

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

Here's one way using a dictionary comprehension.这是使用字典理解的一种方法。 Note that dictionaries are unhashable, so you cannot have a set of dictionaries.请注意,字典是不可散列的,因此您不能拥有一组字典。 You could have the result be a list of dictionaries instead as bellow:你可以得到一个字典列表,而不是如下:

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}]

Your code goes wrong at the zip line.您的代码在高空滑索处出错。 Firstly,首先,

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

while尽管

c = [2, -4]

(sublist, c) works for the first two elements and not the elements satisfying the condition. (sublist, c) 适用于前两个元素,而不适用于满足条件的元素。 To make this work, a different list has to be made consisting of为了完成这项工作,必须制作一个不同的列表,包括

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

But this fails to zip the values because zip does not work on list of lists.但这无法压缩值,因为 zip 不适用于列表列表。 So the solution to this problem comes out to store the c[i] value for the ith element of b.所以这个问题的解决方案就是存储b的第i个元素的c[i]值。 If any sub-element satisfies the condition, update the dictionary, otherwise keep on iterating and changing the value of c[i].如果任何子元素满足条件,则更新字典,否则继续迭代并更改 c[i] 的值。 This method is implemented as follows :-该方法实现如下:-

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