[英]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.