Python3。在值字典中查找数组的值

Python3. Find values of array in values dictionary

我有两个列表。

List all_text - the first value is the key, the second meaning is a set of words.

List keyword_list - list of keywords I want to find in a set of words all_text.

我的代码显示列表 all_text 中的所有值。

我想获得以下结果:

defaultdict(<class 'list'>, {'Z1234': ['earth'], 'Z1207': ['north']})

如何修复下面的代码?

from collections import defaultdict, Counter
all_text = [['Z1234', 'earth total surface area land'], ['Z1207', 'first 
north university']]
keyword_list = ['earth', 'north']

dictions = defaultdict(list)
for key, sentence in all_text:
    dictions[key].extend(sentence.split())

result = defaultdict(list)
for x in dictions.values():
    for i in x:
        for y in keyword_list:
            if i in y:
                result[key].extend(x)
print(result)

>>defaultdict(<class 'list'>, {'Z1207': ['first', 'north', 'university', 
'earth', 'total', 'surface', 'area', 'land']})

这是一种方法。

from collections import defaultdict

all_text = [['Z1234', 'earth total surface area land'],
            ['Z1207', 'first north university']]
keyword_list = ['earth', 'north']

keyword_set = set(keyword_list)

d = defaultdict(list)

for k, v in all_text:
    for w in set(v.split()) & keyword_set:
        d[k].append(w)

# defaultdict(list, {'Z1207': ['north'], 'Z1234': ['earth']})

说明

  • str.split 不带参数将字符串分隔为单词列表。
  • &set 交集的替代语法。

在 python 和 zip 中实际上很容易退出。请参考下面的代码并检查这是否与您想要的完全相同:

all_text = [['Z1234', 'earth total surface area land'], ['Z1207', 'first north university']]
keyword_list = ['earth', 'north']
finaldict = {}
for i,item in zip(keyword_list, all_text):
    finaldict[item[0]] = i
print(finaldict)