在字典列表中找到匹配的值,然后将字符串配对

时间:2019-06-06 14:50:48

标签: python list dictionary for-loop

我在想出可以实现我想要的功能的代码时遇到麻烦。

我有一个使用此结构的词典列表:

word = {'word': 'Dog', 'loc': 160}

它们被添加到for循环的列表中:

words = []

for line in lines:
  word = {'word': line['WordText'], 'loc': line['Location']}
  ...
  words.append(word)

每行都有一个location整数,稍后我需要将文本与该行配对。

我需要在列表中找到键loc的值匹配的所有实例,然后以某种方式将它们配对。

(Python)伪代码:

new_lines = []

for word in words:
  new_line = {'line': '', 'loc': 0}
  if a_word['loc'] == another_word['loc']:
    new_line['line'] = a_word['word'] + another_word['word']
    new_line['loc'] = a_word['loc']
    new_lines.append(new_line)

我知道这不是正确的方法,但是我需要某种if any word['loc'] matches any other word['loc']: then put into list这种东西。

如果不清楚,我想在 loc 值匹配的字典中配对单词

2 个答案:

答案 0 :(得分:1)

您可以建立一个词典,其中每个位置都收集单词列表。然后过滤掉只有一个单词的位置。

from collections import defaultdict

lines = [{'WordText': 'dog',   'Location': 11},
         {'WordText': 'cow',   'Location': 222},
         {'WordText': 'cat',   'Location': 11},
         {'WordText': 'horse', 'Location': 222},
         {'WordText': 'duck',  'Location': 55},
         {'WordText': 'goat',  'Location': 222}]

wordsAtLoc = defaultdict(set)
for line in lines:
    wordsAtLoc[line['Location']].add(line['WordText'])
matches = { loc:list(words) for loc,words in wordsAtLoc.items() if len(words)>1 }   

print(matches)
# {11: ['cat', 'dog'], 222: ['goat', 'horse', 'cow']}

答案 1 :(得分:0)

  

我需要在列表中找到键loc值匹配的所有实例,然后以某种方式将它们配对。

使用默认字典将单词按“ loc”分组。

您可以用它遍历“ d”并做您想做的事。

from collections import defaultdict

d = defaultdict(list)

words = [{'word': 'fog', 'loc': 12}, {'word': 'bird', 'loc': 122}, {'word': 'bag', 'loc': 12},
         {'word': 'main', 'loc': 33}]

for word in words:
    d[word['loc']].append(word['word'])
print(d)

输出

defaultdict(<class 'list'>, {12: ['fog', 'bag'], 122: ['bird'], 33: ['main']})
相关问题