Skip to main content
 首页 » 编程设计

python 3。在值字典中查找数组的值

2025年05月04日16txw1958

我有两个列表。

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 的替代语法十字路口。